【发布时间】:2016-05-19 20:45:35
【问题描述】:
我有一个问题。 假设我有一个通用类,它可以具有其他类的通用属性,甚至可以具有其他类的列表。 如果我有这样的功能
public void Read<T>() where T: class, new()
{
// Create an instance of our generic class
var model = new T();
var properties = typeof(T).GetProperties();
// Loop through the objects properties
for(var property in properties) {
// Set our value
SetPropertyValue(property, model, "test");
}
}
private void SetPropertyValue(PropertyInfo property, object model, string value) {
// Set our property value
property.SetValue(model, value, null);
}
如果我有这样的课程,那就行了:
public class Person
{
public string Name { get; set; }
}
我像这样调用 Read 方法:
Read<Person>();
但如果我的 Person 模型是这样的:
public class Person
{
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company
{
public string Name { get; set; }
}
我尝试再次调用 Read 方法,因为该属性有它自己的属性列表,所以它会失败。 如果它也穿过它们会更好。有没有办法做到这一点?
【问题讨论】:
-
除了泛型之外,只需实现非泛型版本的 Read 方法。从泛型 - 调用非泛型版本不要过多重复代码。然后当你递归时 - 只需调用具有属性类型的非通用版本。无论如何,非通用版本通常都很好。