相关疑难解决方法(0)

如何确定类型是否实现特定的通用接口类型

假设以下类型定义:

public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
Run Code Online (Sandbox Code Playgroud)

当只有受损的类型可用时,如何确定类型是否Foo实现了通用接口IBar<T>

.net c# reflection

211
推荐指数
7
解决办法
8万
查看次数

.NET反射:检测IEnumerable <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)

但这似乎有点间接 - 是否有更直接/更优雅的方式来做到这一点?

.net generics reflection

11
推荐指数
1
解决办法
3991
查看次数

标签 统计

.net ×2

reflection ×2

c# ×1

generics ×1