首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当我只知道T的类型时,如何在T的c#泛型集合中找到T的类型?

当我只知道T的类型时,如何在T的c#泛型集合中找到T的类型?
EN

Stack Overflow用户
提问于 2011-09-02 20:27:19
回答 3查看 282关注 0票数 8

我有一个PropertyInfo数组来表示类中的属性。这些属性中有一些是ICollection<T>类型的,但是T在不同的属性中是不同的-我有一些ICollection<string>,一些ICollection<int>,等等。

通过在类型上使用GetGenericTypeDefinition()方法,我可以很容易地识别出哪些属性是ICollection<>类型,但我发现不可能获得T的类型-上面例子中的int或string。

有没有办法做到这一点?

代码语言:javascript
运行
复制
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
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-09-02 20:32:47

如果您知道它将是ICollection<X>,但不知道X,那么使用GetGenericArguments就很容易了

代码语言:javascript
运行
复制
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>但本身可能是泛型的类型时,就会变得更加困难。听起来你处于一个更好的位置:)

票数 8
EN

Stack Overflow用户

发布于 2011-09-02 20:33:12

我相信这就是你要找的:

代码语言:javascript
运行
复制
typeOfProperty.GetGenericArguments()[0];

例如,它将返回泛型列表的T部分。

票数 4
EN

Stack Overflow用户

发布于 2011-09-02 23:06:38

Jon的解决方案将生成T。根据上下文,您可能需要访问getter返回类型,以便获取int、string等。例如...

代码语言:javascript
运行
复制
// 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());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7283383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档