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

public interface IMyInterface {}

public class MyType : IMyInterface {}

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

当前回答

使用类型。IsAssignableTo(自。net 5.0起):

typeof(MyType).IsAssignableTo(typeof(IMyInterface));

正如在一些评论中所述,IsAssignableFrom可能被认为是“向后”的混淆。

其他回答

任何人搜索这个可能会发现下面的扩展方法很有用:

public static class TypeExtensions
{
    public static bool ImplementsInterface(this Type type, Type @interface)
    {
        if (type == null)
        {
            throw new ArgumentNullException(nameof(type));
        }

        if (@interface == null)
        {
            throw new ArgumentNullException(nameof(@interface));
        }

        var interfaces = type.GetInterfaces();
        if (@interface.IsGenericTypeDefinition)
        {
            foreach (var item in interfaces)
            {
                if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)
                {
                    return true;
                }
            }
        }
        else
        {
            foreach (var item in interfaces)
            {
                if (item == @interface)
                {
                    return true;
                }
            }
        }

        return false;
    }
}

xunit测试:

public class TypeExtensionTests
{
    [Theory]
    [InlineData(typeof(string), typeof(IList<int>), false)]
    [InlineData(typeof(List<>), typeof(IList<int>), false)]
    [InlineData(typeof(List<>), typeof(IList<>), true)]
    [InlineData(typeof(List<int>), typeof(IList<>), true)]
    [InlineData(typeof(List<int>), typeof(IList<int>), true)]
    [InlineData(typeof(List<int>), typeof(IList<string>), false)]
    public void ValidateTypeImplementsInterface(Type type, Type @interface, bool expect)
    {
        var output = type.ImplementsInterface(@interface);
        Assert.Equal(expect, output);
    }
}

修改Jeff的答案以获得最佳性能(感谢Pierre Arnaud的性能测试):

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

查找在给定程序集中实现接口的所有类型:

var implementations = typeof(TypeInTargetAssembly).Assembly.GetTypes()
                          .Where(t => typeof(IMyInterface).IsAssignableFrom(t) && t.IsClass);

我刚刚做了:

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

我希望我能说在哪里I: interface,但interface不是一个通用参数约束选项。课堂离我们很近。

用法:

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

我只是说工具,因为这更直观。我总是得到IsAssignableFrom flip-flopped。

正确答案是

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

正如其他人已经提到的: 本杰明13年4月10日22:21

这当然很容易让人不注意,并得到争论 IsAssignableFrom倒退。我现在用GetInterfaces:p -

好吧,另一种方法是创建一个简短的扩展方法,在某种程度上,满足“最常见”的思维方式(并且同意这是一个非常小的个人选择,使它稍微“更自然”基于个人的喜好):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }
}

为什么不更通用一点呢(好吧,不确定它是否真的那么有趣,好吧,我假设我只是传递另一个“语法”糖):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }

    public static bool IsAssignableTo<TAssignable>(this Type type)
    {
        return IsAssignableTo(type, typeof(TAssignable));
    }
}

我认为这样可能会更自然,但这只是我个人的观点:

var isTrue = michelleType.IsAssignableTo<IMaBelle>();