【发布时间】: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<int>。
这会导致崩溃。
它不仅气味难闻。
【问题讨论】:
-
不确定我是否理解您想要实现的目标。您是否只想指出
ObjectA类型利用ObjectB和ObjectC类型这一事实?除此之外,至少您可以使用Type.GetGenericArguments 来检索列表中使用的类型,而不是尝试解析其ToString()表示。 -
@Pete :确实非常接近。但是,我从不使用泛型类型。
-
@ChrisSinclair :是的,这就是我想要的。 Lee 的回答也使用了这个。
标签: c# reflection