假设以下类型定义:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
当只有编码后的类型可用时,如何确定类型 Foo
是否实现了泛型接口 IBar<T>
?
假设以下类型定义:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
当只有编码后的类型可用时,如何确定类型 Foo
是否实现了泛型接口 IBar<T>
?
通过使用TcKs的答案,也可以使用以下LINQ查询来完成:
bool isBar = foo.GetType().GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IBar<>));
public interface IFoo<T> : IBar<T> {}
public class Foo : IFoo<Foo> {}
var implementedInterfaces = typeof( Foo ).GetInterfaces();
foreach( var interfaceType in implementedInterfaces ) {
if ( false == interfaceType.IsGeneric ) { continue; }
var genericType = interfaceType.GetGenericTypeDefinition();
if ( genericType == typeof( IFoo<> ) ) {
// do something !
break;
}
}
public static bool Implements<I>(this Type type, I @interface) where I : class
{
if(((@interface as Type)==null) || !(@interface as Type).IsInterface)
throw new ArgumentException("Only interfaces can be 'implemented'.");
return (@interface as Type).IsAssignableFrom(type);
}
示例用法:
var testObject = new Dictionary<int, object>();
result = testObject.GetType().Implements(typeof(IDictionary<int, object>)); // true!
我正在使用稍微简化版本的@GenericProgrammers扩展方法:
public static bool Implements<TInterface>(this Type type) where TInterface : class {
var interfaceType = typeof(TInterface);
if (!interfaceType.IsInterface)
throw new InvalidOperationException("Only interfaces can be implemented.");
return (interfaceType.IsAssignableFrom(type));
}
使用方法:
if (!featureType.Implements<IFeature>())
throw new InvalidCastException();
如果您需要一个支持泛型基类型和接口的扩展方法,我对sduplooy的答案进行了扩展:
public static bool InheritsFrom(this Type t1, Type t2)
{
if (null == t1 || null == t2)
return false;
if (null != t1.BaseType &&
t1.BaseType.IsGenericType &&
t1.BaseType.GetGenericTypeDefinition() == t2)
{
return true;
}
if (InheritsFrom(t1.BaseType, t2))
return true;
return
(t2.IsAssignableFrom(t1) && t1 != t2)
||
t1.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == t2);
}
要完全解决类型系统问题,我认为您需要处理递归,例如: IList<T>
:ICollection<T>
:IEnumerable<T>
,否则您将不知道 IList<int>
最终实现了 IEnumerable<>
。
/// <summary>Determines whether a type, like IList<int>, implements an open generic interface, like
/// IEnumerable<>. Note that this only checks against *interfaces*.</summary>
/// <param name="candidateType">The type to check.</param>
/// <param name="openGenericInterfaceType">The open generic type which it may impelement</param>
/// <returns>Whether the candidate type implements the open interface.</returns>
public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
Contract.Requires(candidateType != null);
Contract.Requires(openGenericInterfaceType != null);
return
candidateType.Equals(openGenericInterfaceType) ||
(candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) ||
candidateType.GetInterfaces().Any(i => i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType));
}
您需要针对泛型接口的构造类型进行检查。
您需要执行以下操作:
foo is IBar<String>
因为 IBar<String>
代表了这个构造类型。你必须这样做的原因是,如果在你的检查中 T
没有定义,编译器就不知道你是指 IBar<Int32>
还是 IBar<SomethingElse>
。
首先 public class Foo : IFoo<T> {}
无法编译,因为你需要指定一个类而不是 T。但是假设你像这样做:public class Foo : IFoo<SomeClass> {}
然后,如果你执行:
Foo f = new Foo();
IBar<SomeClass> b = f as IBar<SomeClass>;
if(b != null) //derives from IBar<>
Blabla();
var genericType = typeof(ITest<>);
Console.WriteLine(typeof(Test).GetInterfaces().Any(x => x.GetGenericTypeDefinition().Equals(genericType))); // prints: "True"
interface ITest<T> { };
class Test : ITest<string> { }
GetGenericTypeDefinition()
之前检查类型是否为泛型通常是一个好主意,否则可能会引发异常。 - Christian Klemm
typeof(IBar<,,,>)
with commas acting like placeholders小改动:如果 IBar 有多个泛型类型,你需要这样表示:typeof(IBar<,,,>)
,其中逗号充当占位符。 - Rob Von Nesselrodetype.Implements(typeof(IBar<>))
非常干净地添加了这个功能,并覆盖了所有情况。 - Michael Brown