我对此感到困惑。但这是我想要做的。这里是类结构:通过泛型加载类
public class Order
{
public Int32 orderID { get; set; }
public Int32 CustomerID { get; set; }
public Int32 ProductID { get; set; }
public string OrderName { get; set; }
public Product ProductDetails { get; set; }
public Customer CustomerDetails { get; set; }
}
public class Product
{
public Int32 ProductID { get; set; }
public string Name { get; set; }
}
public class Customer
{
public Int32 CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
我建立一个通用的方法,即采用XML内容,并创建和装载传入的对象类型的实例。我得到了产品和客户的工作。但是当涉及到订单时,它会让人感到困惑。
public static T LoadObject<T>(string Contents) where T : new()
{
T obj = new T();
foreach (PropertyInfo property in typeof (T).GetProperties())
{
if (property.PropertyType.IsValueType || property.PropertyType.IsPrimitive)
{
object propValue = Convert.ChangeType(GetValue(property.PropertyType, Contents),
property.PropertyType);
property.SetValue(obj, propValue, null);
}
else
{
//Type typeArgument = property.PropertyType;
//Type genericClass = t
//object propValue = LoadObject<> (dr);
//property.SetValue(obj, propValue, null);
}
}
return obj;
}
如何以递归方式调用此命令,以便订购客户和产品?
你不能使用XmlSerializer来完成这个吗? –
这些类都很小,所以我不太明白你为什么需要这样一个通用的解决方案(YAGNI原则......)。我只是为它们中的每一个实现了一些“FromXml”方法,并且使它成为接口方法或其他东西。考虑到反射实际上非常缓慢 - 当你需要处理数以千计的订单时,它会很明显。一遍又一遍地检索同一个PropertyInfo是很昂贵的。 –
这只是我提出的一个例子,以更好地解释问题。事实上,这些不是课程。而且输入也不一定是XML。 – katie77