我对此感到困惑,似乎无法理解它,所以希望有人能给我指出正确的方向。
我有一个类如下:
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 aDictionary
withDictionary<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/