c#中的反射是否提供了一种方法来确定某个给定的System。类型类型模型一些接口?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
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可能被认为是“向后”的混淆。
其他回答
是什么
if(MyType as IMyInterface != null)
?
使用类型。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);
使用类型。IsAssignableFrom:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType));