【问题标题】:How to find the type contained within a (strongly typed) collection? [duplicate]如何找到(强类型)集合中包含的类型? [复制]
【发布时间】:2013-02-07 16:36:09
【问题描述】:

我有一个看起来像这样的课程:

public class ObjectA
{
    public ObjectB OneObject { get; set; }

    public List<ObjectC> ManyObject { get; set; }
}

然后是一个读取类包含的内容并返回属性类型的函数:

source = typeof(*some ObjectA*)

var classprops = source.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.PropertyType.IsClass && !x.PropertyType.IsValueType && x.PropertyType.Name != "String");

foreach (var prop in classprops)
{
    var classnamespace = CommonTool.GetNamespaceFromProp(prop);

    if ((prop.PropertyType).Namespace == "System.Collections.Generic")
    {
        string newprop = prop.ToString();
        int start = newprop.IndexOf("[")+1;
        int end = newprop.IndexOf("]");
        newprop = newprop.Substring(start, end-start);
        newprop = string.Format("{0}, Env.Project.Entites", newprop);
        classnamespace = newprop;
    }
    //some code to read attributes on the properties...
}

我的问题是if ((prop.PropertyType).Namespace == "System.Collections.Generic") 中的内容。它闻起来

有更好的方法吗?

编辑:

应用程序中的一个类使用List&lt;int&gt;
这会导致崩溃。
它不仅气味难闻。

【问题讨论】:

  • 不确定我是否理解您想要实现的目标。您是否只想指出ObjectA 类型利用ObjectBObjectC 类型这一事实?除此之外,至少您可以使用Type.GetGenericArguments 来检索列表中使用的类型,而不是尝试解析其ToString() 表示。
  • @Pete :确实非常接近。但是,我从不使用泛型类型。
  • @ChrisSinclair :是的,这就是我想要的。 Lee 的回答也使用了这个。

标签: c# reflection


【解决方案1】:

如果要检查属性是否为泛型集合,并获取元素类型,可以检查它是否包含IEnumerable&lt;T&gt;,如果是则获取类型T

Type propType = prop.PropertyType;
if (propType.IsGenericType)
{
    Type enumerableType = propType.GetInterfaces().FirstOrDefault(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IEnumerable<>)));
    if(enumerableType != null)
    {
        Type elementType = enumerableType.GetGenericArguments()[0];
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 2014-01-21
    • 1970-01-01
    • 2021-09-19
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 2010-11-30
    相关资源
    最近更新 更多