如何查找(强类型)集合中包含的类型?

时间:2013-02-07 16:36:09

标签: c# reflection

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

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<int> 这导致了崩溃 它不仅闻起来很糟糕。

1 个答案:

答案 0 :(得分:3)

如果你想检查属性是否是泛型集合,并获取元素类型,你可以检查它是否为IEnumerable<T>,并获取类型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];
    }
}
相关问题