2011-08-08 91 views
0

我对此感到困惑。但这是我想要做的。这里是类结构:通过泛型加载类

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; 
    } 

如何以递归方式调用此命令,以便订购客户和产品?

+0

你不能使用XmlSerializer来完成这个吗? –

+0

这些类都很小,所以我不太明白你为什么需要这样一个通用的解决方案(YAGNI原则......)。我只是为它们中的每一个实现了一些“FromXml”方法,并且使它成为接口方法或其他东西。考虑到反射实际上非常缓慢 - 当你需要处理数以千计的订单时,它会很明显。一遍又一遍地检索同一个PropertyInfo是很昂贵的。 –

+0

这只是我提出的一个例子,以更好地解释问题。事实上,这些不是课程。而且输入也不一定是XML。 – katie77

回答

0

您可以使用反射来进行递归调用:

public void Test<T>() 
{ 
    var methodInfo = GetType().GetMethod("Test"); 
    methodInfo = methodInfo.MakeGenericMethod(typeof(int)); 
    methodInfo.Invoke(this, new object[0]); 
} 
0

的事情是,你不能叫LoadObject<T>其中T将是property.PropertyType,因为你不能在编译时使用带有参数未知的仿制药。我自己也遇到了这样的问题,我曾经问过一个与你的问题有些相关的问题:Generic static class - retrieving object type in run-time(相关 - 如果我理解你的话,那就是,否则不管它)。

0

通常,在这种情况下您要做的是在Order类中创建Customer和Product实例,并在Order类上使用Load方法来填充Order,然后填充Customer实例和Product实例。

public class Order 
{ 
    public void LoadOrder(int orderID) 
    { 
     //load order 

     //load customer from order 

     //load product from order 
    } 

    public Customer Cust 
    { 
     get; set; 
    } 
    public Product Prod 
    { 
     get; set; 
    } 
} 

我知道你问的是有点不同,但希望这有助于。