开发者

How to check that type is inherited from some interface c#

开发者 https://www.devze.com 2023-01-28 04:36 出处:网络
I have following: Assembly asm = Assembly.Ge开发者_运维问答tAssembly(this.GetType()); foreach (Type type in asm.GetTypes())

I have following:

Assembly asm = Assembly.Ge开发者_运维问答tAssembly(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.


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.


Check out IsAssignableFrom http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx


Hi You can use type.GetInterfaces() or type.GetInterface() to get the interfaces which the type implements.


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();  
                }
            }
        }
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消