2011-11-10 61 views
0

我創建了對象類列表並從CreateListFromTable方法返回。但總是虛擬方法正在調用並拋出異常。數據未加載到列表中。對象列表無法正確加載?

可能是什麼問題?

public static List<Customer> GetCustomer(string ID) 
    { 
     DataTable dt = new DataTable(); 
     try 
     { 
      DatabaseGateway da = new DatabaseGateway(); 
      dt = da.QueryForDataTable("proc_GetCustomer", ID);     
     } 
     catch (Exception ex) 
     { 
      LogMessage(ex.Message + ": " + ex.StackTrace, EventLogEntryType.Error); 
     } 

     return CreateListFromTable<Customer>(dt);   


    } 

protected static List<T> CreateListFromTable<T>(DataTable dt) where T : BusinessObject, new() 
    { 
     List<T> list = new List<T>(); 
     try 
     {   
      if (dt != null) 
      foreach (DataRow row in dt.Rows) 
      { 
       T t = new T(); 
       t.Load(row); 
       list.Add(t); 
      } 
     } 
     catch (Exception exception) 
     { 


     } 
     return list; 
    } 
    /// <summary> 
    /// Virtual method which should be overriden by inherited types that support loading. 
    /// </summary> 
    /// <param name="row"></param> 
    protected virtual void Load(DataRow row) 
    { 
     throw new NotSupportedException("The object of type '" + this.GetType().Name + 
      "' does not support loading from DataRow."); 
    } 
+1

什麼可能是例外? – GazTheDestroyer

+0

{「'Customer'類型的對象不支持從DataRow加載。」} – James123

回答

0

是否Customer繼承BusinessObject

public class Customer : BusinessObject 

而且,你正確地覆蓋的方法(從這個類假定代碼爲Load方法是BusinessObject)?

protected override void Load(DataRow row) 

另外,我注意到,Load方法是protected,它看起來像你呼籲t公共Load方法。這可能會導致一些混淆,因爲您無法使用公共方法覆蓋受保護的方法(編譯器錯誤:Inconsistent accessibility: base class 'BaseClass.ProtectedMethod' is less accessible than class 'DerivedClass.ProtectedMethod'),因此實際上調用了哪些方法。

0

你得趕上每次迭代,而不是包裝循環。

+0

它正在處理其他類而不是客戶。 – James123

0

您可以在LINQ中使用可擴展的.ToList()方法將數據表傳遞給列表。

0

你有沒有在Customer類中看起來像這樣的方法?

protected override void Load(DataRow row) 
{ 
    ... 
} 

此外,您還可以使BusinessObject的抽象類,讓Load方法abstract而不是virtual,以確保不會發生這種情況?