假设以下类型定义:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
Run Code Online (Sandbox Code Playgroud)
当只有受损的类型可用时,如何确定类型是否Foo实现了通用接口IBar<T>?
我正在尝试检测Type对象的特定实例是否是通用的"IEnumerable"...
我能想到的最好的是:
// theType might be typeof(IEnumerable<string>) for example... or it might not
bool isGenericEnumerable = theType.GetGenericTypeDefinition() == typeof(IEnumerable<object>).GetGenericTypeDefinition()
if(isGenericEnumerable)
{
Type enumType = theType.GetGenericArguments()[0];
etc. ...// enumType is now typeof(string)
Run Code Online (Sandbox Code Playgroud)
但这似乎有点间接 - 是否有更直接/更优雅的方式来做到这一点?