Reputation: 4232
I have following:
Assembly asm = Assembly.GetAssembly(this.GetType());
foreach (Type type in asm.GetTypes())
{
MyAttribute attr = Attribute.GetCustomAttribute(type, typeof(MyAttribute)) as MyAttribute;
if(attr != null && [type is inherited from Iinterface])
{
...
}
}
How can i check that type is inherited from MyInterface? Does is keywork will work in this way?
Thank you.
Upvotes: 33
Views: 25777
Reputation: 347
You can use type.IsAssignableTo(typeof(IInterface))
, as it returns true
in one of the following cases, as described in the MSDN:
Upvotes: -1
Reputation: 11
Given worst case scenario;
if you are using reflection over all properties in a class...
public List<PropertyInfo> FindProperties(Type TargetType) {
MemberInfo[] _FoundProperties = TargetType.FindMembers(MemberTypes.Property,
BindingFlags.Instance | BindingFlags.Public, new
MemberFilter(MemberFilterReturnTrue), TargetType);
List<PropertyInfo> _MatchingProperties = new List<PropertyInfo>();
foreach (MemberInfo _FoundMember in _FoundProperties) {
_MatchingProperties.Add((PropertyInfo)_FoundMember); }
return _MatchingProperties;
}
IInterface is some generic interface
public void doSomthingToAllPropertiesInDerivedClassThatImplementIInterface() { IList<PropertyInfo> _Properties = FindProperties(this.GetType()); foreach (PropertyInfo _Property in _Properties) { if (_Property.PropertyType.GetInterfaces().Contains(typeof(IInterface))) { if ((IInterface)_Property.GetValue(this, null) != null) { ((IInterface)_Property.GetValue(this, null)).SomeIInterfaceMethod(); } } } }
Upvotes: -1
Reputation: 1721
Realise this is very late, but leaving it here for reference: I found the is operator does the job - from MSDN - http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx
Using resharper on Jon Skeets answer, gave me "is" as a suggestion as well.
Upvotes: -2
Reputation: 1500515
No, is
only works for checking the type of an object, not for a given Type
. You want Type.IsAssignableFrom
:
if (attr != null && typeof(IInterface).IsAssignableFrom(type))
Note the order here. I find that I almost always use typeof(...)
as the target of the call. Basically for it to return true, the target has to be the "parent" type and the argument has to be the "child" type.
Upvotes: 60
Reputation: 9114
Hi
You can use type.GetInterfaces() or type.GetInterface()
to get the interfaces which the type implements.
Upvotes: 3
Reputation: 12567
Check out IsAssignableFrom http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx
Upvotes: 7