How to determine if a type implements an interface

2019-01-03 19:46发布

Does reflection in C# offer a way to determine if some given System.Type type models some interface?

public interface IMyInterface {}

public class MyType : IMyInterface {}

// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);

11条回答
闹够了就滚
2楼-- · 2019-01-03 20:08

IsAssignableFrom is now moved to TypeInfo:

typeof(ISMSRequest).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-03 20:09

Modifying Jeff's answer for optimal performance (thanks to performance test by Pierre Arnaud):

var type = typeof(MyType);
var implementsInterface = typeof(IMyInterface).IsAssignableFrom(type) && type.IsClass;

To find all types that implement an interface in a given Assembly:

var implementations = typeof(TypeInTargetAssembly).Assembly.GetTypes()
                          .Where(t => typeof(IMyInterface).IsAssignableFrom(t) && t.IsClass);
查看更多
Bombasti
4楼-- · 2019-01-03 20:09

I just did:

public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}

I wish I could have said where I : interface, but interface is not a generic parameter constraint option. class is as close as it gets.

Usage:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

I just said Implements because that's more intuitive. I always get IsAssignableFrom flip-flopped.

查看更多
Juvenile、少年°
5楼-- · 2019-01-03 20:09

What about

typeof(IWhatever).GetTypeInfo().IsInterface
查看更多
看我几分像从前
6楼-- · 2019-01-03 20:14
    public static bool ImplementsInterface( this Type type, Type ifaceType ) {
        Type[] intf = type.GetInterfaces();
        for ( int i = 0; i < intf.Length; i++ ) {
            if ( intf[ i ] == ifaceType ) {
                return true;
            }
        }
        return false;
    }

I think this is the correct release, for three reasons:

1) It uses GetInterfaces and not IsAssignableFrom, it's faster since IsAssignableFrom eventually after several checks does call GetInterfaces.
2) It iterates over the local array, so there will be no bounds checks.
3) It uses the == operator which is defined for Type, so probably is safer than the Equals method (that the Contains call, will eventually use).

查看更多
登录 后发表回答