C# 确定字段是否使用常规参数

C# 确定字段是否使用常规参数,c#,generics,reflection,C#,Generics,Reflection,我一直对此感到困惑,似乎无法让我的头左右,所以希望有人能给我指出正确的方向 我的课程如下: public class Foo<T> { public List<T> Data; } 公共类Foo { 公开名单数据; } 现在,我正在编写代码来反映这个类,并希望找到一种方法来确定字段数据是否使用了泛型参数 我最初的方法是继续尽可能多地降低级别,一旦我将IsGenericParameter字段设置为true,我宁愿反映类型名称,而不是在那里放置一个“Generic

我一直对此感到困惑,似乎无法让我的头左右,所以希望有人能给我指出正确的方向

我的课程如下:

public class Foo<T>
{
    public List<T> Data;
}
公共类Foo
{
公开名单数据;
}
现在,我正在编写代码来反映这个类,并希望找到一种方法来确定字段数据是否使用了泛型参数

我最初的方法是继续尽可能多地降低级别,一旦我将IsGenericParameter字段设置为true,我宁愿反映类型名称,而不是在那里放置一个“Generic Argument”字符串,但是我似乎无法让它按我希望的方式工作


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

您想要的是
IsGenericType
,而不是
IsGenericParameter

bool isGeneric = typeof(Foo<int>).GetField("Data").FieldType.IsGenericType;
如果
数据
字段是带有
字典
字典,该怎么办。如何确定使用泛型参数的类型

对类型调用
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
);
公共类Foo
{
公共字典栏;
}
Type[]types=typeof(Foo).GetField(“Bar”).FieldType.GetGenericArguments();
Console.WriteLine(“{0}\n{1}”,
类型[0]。IsGenericParameter,//false,类型为字符串
类型[1]。IsGenericParameter//true,类型为T
);

基本上,
IsGenericParameter
是在查看类型的泛型参数时使用的,以确定它是泛型的还是有指定的类型。

以下是如何区分依赖于类类型参数的泛型类型和不依赖于类类型参数的泛型类型。考虑这个例子:

class Foo<T> {
    public List<T> field1;   // You want this field
    public List<int> field2; // not this field
}
此代码:


初始的
System.Type
实例是什么?是
typeof(Foo)
还是类似于
typeof(Foo)
?Hi@dasblinkenlight实例是Foo。为了添加这一点,我然后遍历字段,因此当使用Foo时,我进入数据字段,在列表之后,字符串本身没有将'IsGenericParameter'设置为true。只是为了确定,您想知道,该数据使用泛型类型?您要查找的是
IsGenericType
?e、 g.
typeof(Foo).GetField(“数据”).FieldType.IsGenericType
好的,这似乎是合乎逻辑的,但如果数据字段是一个带字典的字典呢。。。我如何确定哪种类型使用了泛型参数?谢谢-这也帮助我找到了正确的位置,但上面的用户只是稍微快了一点,所以我认为将其标记为正确答案是公平的:)
class Foo<T> {
    public List<T> field1;   // You want this field
    public List<int> field2; // not this field
}
var g = typeof(Foo<string>).GetGenericTypeDefinition();
var a = g.GetGenericArguments();
foreach (var f in g.GetFields()) {
    var ft = f.FieldType;
    if (!ft.IsGenericType) continue;
    var da = ft.GetGenericArguments();
    if (da.Any(xt => a.Contains(xt))) {
        Console.WriteLine("Field {0} uses generic type parameter", f.Name);
    } else {
        Console.WriteLine("Field {0} does not use generic type parameter", f.Name);
    }
}
Field field1 uses generic type parameter
Field field2 does not use generic type parameter