我有一个PropertyInfo数组来表示类中的属性。这些属性中有一些是ICollection<T>类型的,但是T在不同的属性中是不同的-我有一些ICollection<string>,一些ICollection<int>,等等。
通过在类型上使用GetGenericTypeDefinition()方法,我可以很容易地识别出哪些属性是ICollection<>类型,但我发现不可能获得T的类型-上面例子中的int或string。
有没有办法做到这一点?
IDocument item
PropertyInfo[] documentProperties = item.GetType().GetProperties();
PropertyInfo property = documentProperties.First();
Type typeOfProperty = property.PropertyType;
if (typeOfProperty.IsGenericType)
{
Type typeOfProperty = property.PropertyType.GetGenericTypeDefinition();
if (typeOfProperty == typeof(ICollection<>)
{
// find out the type of T of the ICollection<T>
// and act accordingly
}
}发布于 2011-09-02 20:32:47
如果您知道它将是ICollection<X>,但不知道X,那么使用GetGenericArguments就很容易了
if (typeOfProperty.IsGenericype)
{
Type genericDefinition = typeOfProperty.GetGenericTypeDefinition();
if (genericDefinition == typeof(ICollection<>)
{
// Note that we're calling GetGenericArguments on typeOfProperty,
// not genericDefinition.
Type typeArgument = typeOfProperty.GetGenericArguments()[0];
// typeArgument is now the type you want...
}
}当类型是实现了ICollection<T>但本身可能是泛型的类型时,就会变得更加困难。听起来你处于一个更好的位置:)
发布于 2011-09-02 20:33:12
我相信这就是你要找的:
typeOfProperty.GetGenericArguments()[0];例如,它将返回泛型列表的T部分。
发布于 2011-09-02 23:06:38
Jon的解决方案将生成T。根据上下文,您可能需要访问getter返回类型,以便获取int、string等。例如...
// The following example will output "T"
typeOfProperty = property.PropertyType.GetGenericTypeDefinition();
Type genericDefinition = typeOfProperty.GetGenericTypeDefinition();
if (genericDefinition == typeof(ICollection<>))
{
Type t1 = typeOfProperty.GetGenericArguments()[0];
Console.WriteLine(t1.ToString());
}
// Instead you might need to do something like the following...
// This example will output the declared type (e.g., "Int32", "String", etc...)
typeOfProperty = property.GetGetMethod().ReturnType;
if (typeOfProperty.IsGenericType)
{
Type t2 = typeOfProperty.GetGenericArguments()[0];
Console.WriteLine(t2.ToString());
}https://stackoverflow.com/questions/7283383
复制相似问题