c#中的反射是否提供了一种方法来确定某个给定的System。类型类型模型一些接口?

public interface IMyInterface {}

public class MyType : IMyInterface {}

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

当前回答

正确答案是

typeof(MyType).GetInterface(nameof(IMyInterface)) != null;

然而,

typeof(MyType).IsAssignableFrom(typeof(IMyInterface));

可能会返回错误的结果,如下面的代码所示:

    static void TestIConvertible()
    {
        string test = "test";
        Type stringType = typeof(string); // or test.GetType();

        bool isConvertibleDirect = test is IConvertible;
        bool isConvertibleTypeAssignable = stringType.IsAssignableFrom(typeof(IConvertible));
        bool isConvertibleHasInterface = stringType.GetInterface(nameof(IConvertible)) != null;

        Console.WriteLine($"isConvertibleDirect: {isConvertibleDirect}");
        Console.WriteLine($"isConvertibleTypeAssignable: {isConvertibleTypeAssignable}");
        Console.WriteLine($"isConvertibleHasInterface: {isConvertibleHasInterface}");
    }

结果:

 isConvertibleDirect: True
 isConvertibleTypeAssignable: False
 isConvertibleHasInterface: True

其他回答

使用类型。IsAssignableFrom:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

是什么

if(MyType as IMyInterface != null)

?

如果你不需要使用反射,你有一个对象,你可以使用这个:

if(myObject is IMyInterface )
{
 // it's implementing IMyInterface
}

是什么

typeof(IWhatever).GetTypeInfo().IsInterface
typeof(IMyInterface).IsAssignableFrom(someclass.GetType());

or

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));