[英]System.Reflection - How can I get the PropertyInfo of the sublevel Types?
I have got three classes as follows: 我有三节课,如下所示:
public class TestA
{
public string Str1 { get; set; }
public string Str2 { get; set; }
public List<TestB> LstTestBs { get; set; }
public TestC ObjTestC { get; set; }
}
public class TestB
{
public string Str3 { get; set; }
public string Str4 { get; set; }
}
public class TestC
{
public string Str5 { get; set; }
}
I have tried: 我努力了:
var prop = typeof (TestA).GetProperties();
But, it is giving only the PropertyInfo for the four members inside TestA. 但是,它仅给出TestA内部四个成员的PropertyInfo。 I need to get the PropertyInfo for all the members in the TestA, TestB and TestC classes.
我需要获取TestA,TestB和TestC类中所有成员的PropertyInfo。
Please help... Thanks in advance, San 请帮助...预先感谢,圣
Thanks for the help everyone. 感谢大家的帮助。 I have got the answer.
我有答案。
var prop = typeof (TestA).GetProperties();
for (int i=0;i<prop.Count();i++)
{
var propertyInfo = prop[i];
if (propertyInfo.PropertyType.Namespace != "System")
{
if (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof (List<>))
{
Type itemType = propertyInfo.PropertyType.GetGenericArguments()[0];
var listObjectProperties = itemType.GetProperties();
prop = prop.Union(listObjectProperties).ToArray();
}
else
{
var childProp = propertyInfo.PropertyType.GetProperties();
prop = prop.Union(childProp).ToArray();
}
}
}
If you put all your classes in the same namespace, you can collect the properties by enumerating the classes in the namespace, instead of mining the property structure: 如果将所有类放在同一个名称空间中,则可以通过枚举名称空间中的类来收集属性,而不是挖掘属性结构:
Getting all types in a namespace via reflection 通过反射获取名称空间中的所有类型
SLaks is right. SLaks是对的。 You should do this recursively.
您应该递归执行此操作。 See wikipedia's article on Recursion for more information on the concept.
有关此概念的更多信息,请参见Wikipedia关于递归的文章 。 For example, in your case, this is the general idea:
例如,在您的情况下,这是一般的想法:
public void AddPropertiesAndChildPropertiesToList(Type type, List<PropertyInfo> list)
{
var properties = type.GetProperties();
list.AddRange(properties);
foreach (var property in properties)
{
// recursive methods are ones that call themselves, like this...
AddPropertiesAndChildPropertiesToList(property.PropertyType, list);
}
}
Note that this example is lacking several things: 请注意,此示例缺少几件事:
Stack<Type> alreadyVisited
parameter. Stack<Type> alreadyVisited
参数跟踪您去过的地方来解决此问题。 If you find you've been asked to add the list of properties for a type you've already visited, just return
out of the method instead, or throw an exception. return
该方法,否则抛出异常。 alreadyVisited
stack would be useful here, too. alreadyVisited
堆栈也将很有用。 List<TestB>
in any useful way. List<TestB>
。 For that, you probably need to figure out whether the type has an indexer, and then the properties of the type that is returned by that indexer.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.