How to use reflection to determine if a class is internal?
As the title says, how do you use reflection to check if a class definition is defined as internal? "typeof(...)" returns certain properties shown below but not whether a class is defined as internal. Looked on Google but all I could find were lots of articles about running internal or protected methods using reflection. It's not the methods I'm interested in this case, but the class definition.
var type = typeof(Customer);
Assert.IsTrue(type.IsClass);
Assert.That(type.IsAbstract, Is.EqualTo(isAbstract));
Assert.That(type.IsPublic, Is.EqualTo(isPublic));
Assert.That(type.IsPublic, Is.EqualTo(isPublic));
Assert.Tha开发者_如何学编程t(type.IsSealed, Is.EqualTo(isSealed));
Assert.That(type.IsSerializable, Is.EqualTo(isSerializable));
This is a classic issue. From MSDN:
The C# keywords
protectedandinternalhave no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL areFamilyandAssembly. To identify aninternalmethod using Reflection, use theIsAssemblyproperty. To identify aprotected internalmethod, use theIsFamilyOrAssembly.
Reflection does not expose a way on Type check if it is internal, protected or protected internal.
Does the IsVisible method give you the value you are looking for?
Here are some functions guaranteed to give the correct visibility of the type (probably an overkill implementation):
bool isPublic(Type t) {
return
t.IsVisible
&& t.IsPublic
&& !t.IsNotPublic
&& !t.IsNested
&& !t.IsNestedPublic
&& !t.IsNestedFamily
&& !t.IsNestedPrivate
&& !t.IsNestedAssembly
&& !t.IsNestedFamORAssem
&& !t.IsNestedFamANDAssem;
}
bool isInternal(Type t) {
return
!t.IsVisible
&& !t.IsPublic
&& t.IsNotPublic
&& !t.IsNested
&& !t.IsNestedPublic
&& !t.IsNestedFamily
&& !t.IsNestedPrivate
&& !t.IsNestedAssembly
&& !t.IsNestedFamORAssem
&& !t.IsNestedFamANDAssem;
}
// only nested types can be declared "protected"
bool isProtected(Type t) {
return
!t.IsVisible
&& !t.IsPublic
&& !t.IsNotPublic
&& t.IsNested
&& !t.IsNestedPublic
&& t.IsNestedFamily
&& !t.IsNestedPrivate
&& !t.IsNestedAssembly
&& !t.IsNestedFamORAssem
&& !t.IsNestedFamANDAssem;
}
// only nested types can be declared "private"
bool isPrivate(Type t) {
return
!t.IsVisible
&& !t.IsPublic
&& !t.IsNotPublic
&& t.IsNested
&& !t.IsNestedPublic
&& !t.IsNestedFamily
&& t.IsNestedPrivate
&& !t.IsNestedAssembly
&& !t.IsNestedFamORAssem
&& !t.IsNestedFamANDAssem;
}
Ehh, I'm not quite sure, but e.g.
Public Function PublicFriendOrPrivate(t As Type) As String
If t.IsPublic Then
Return "Public"
Else
If t.IsNotPublic AndAlso t.IsNested Then
Return "Private"
Else
Return "Friend"
End If
End If
End Function
'Note 'Friend' equals 'Internal' in C#.
加载中,请稍侯......
精彩评论