c# - 确定字段是否使用通用参数

标签 c# generics reflection

我对此感到困惑,似乎无法理解它,所以希望有人能给我指出正确的方向。

我有一个类如下:

public class Foo<T>
{
    public List<T> Data;
}

现在我正在编写代码来反射(reflect)此类,并想找出一种方法来确定字段 Data 是否使用了通用参数。

我最初的方法是继续尽可能多地降低级别,一旦我将 IsGenericParameter 字段设置为 true,我宁愿不反射(reflect)类型名称,而是在那里放置一个“通用参数”字符串,但是我不能似乎让它按照我想要的方式工作。

我环顾四周,但目前我发现的每一个解决方案似乎都指向了死胡同。

最佳答案

你想要IsGenericType , 不是 IsGenericParameter :

bool isGeneric = typeof(Foo<int>).GetField("Data").FieldType.IsGenericType;

如果您想知道 List 的参数是通用的,那么你必须再往下看一层:

bool isGeneric = typeof(Foo<>).GetField("Data")
                                 .FieldType
                                 .GetGenericArguments()[0] // only generic argument to List<T>
                                 .IsGenericParameter;

what if Data field was a Dictionary with Dictionary<string, T>. How would I determine which type was using a generic parameter?

调用GetGenericArguments在类型上并查看结果数组中的每种类型

public class Foo<T>
{
    public Dictionary<string, T> Bar;
}

Type[] types = typeof(Foo<>).GetField("Bar").FieldType.GetGenericArguments();

Console.WriteLine("{0}\n{1}",
    types[0].IsGenericParameter,  // false, type is string
    types[1].IsGenericParameter   // true,  type is T
);

基本上,IsGenericParameter在查看类型的泛型参数以查看它是否是泛型或是否具有特定类型时使用。

关于c# - 确定字段是否使用通用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40178877/

相关文章:

c# - 运营商 : "bool++" in C#

Java泛型方法参数传递问题

c# - 为什么 Type.GetFields() 不返回基类中的支持字段?

Java反射调用不起作用

c# - Ajax 方法调用

c# - 如何在同一查询中使用 DISTINCT 和 VALUE?

c# - 创建一个采用泛型类型的 IEnumerable 类型的方法

c# - 获取枚举类型中的元素数量并迭代它们

c# - 过滤 ObservableCollection

java - 为某些类型扩展泛型类?