Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the accessibility of a MemberInfo instance?

I know the BindingFlags are used to fetch public and non-public members from a Type.

But is there a way to determine if a MemberInfo instance (or derived like PropertyInfo, MethodInfo) is public or not (after it was returned from one of the methods on Type)?

like image 600
obiwanjacobi Avatar asked Oct 14 '10 07:10

obiwanjacobi


2 Answers

PropertyInfo, MethodBase etc each have an Attributes property which has this information - but there's nothing in MemberInfo, because each kind of member has its own kind of attributes enum. Hideous as it is, I think you may need to treat each subclass of MemberInfo separately :( You can probably switch on MemberInfo.MemberType and then cast, which will be slightly nicer than lots of as/test-for-null branches, but it's still not ideal :(

if (member.MemberType == MemberTypes.Property)
{
    var property = (PropertyInfo) member;
    ...
}
like image 153
Jon Skeet Avatar answered Oct 07 '22 20:10

Jon Skeet


You can try ie:

var isPublic = memberInfo.MemberType switch
{
  MemberTypes.Field => ((FieldInfo)memberInfo).IsPublic,
  MemberTypes.Property => ((PropertyInfo)memberInfo).GetAccessors().Any(MethodInfo => MethodInfo.IsPublic),
  _ => false
};

For properties this return true if there is any public accessor which I think is what you're after

like image 1
kofifus Avatar answered Oct 07 '22 18:10

kofifus