2017-02-28 30 views
0

目前,我有以下2類:傳遞類作爲參數,並讓產生的類的屬性動態地C#

public class FirstClass 
    { 
     public string Username { get; set; } 
     public string Fullname { get; set; } 
     public string Email { get; set; } 
    } 

public class SecondClass 
    { 
     public string Username { get; set; } 
     public string Fullname { get; set; } 
     public string Email { get; set; } 
     public int Age { get; set; } 
    } 

我結合來自像下面的數據庫中的那些類的屬性,並且我以爲我會一個通用的方法來調用數據庫,作爲唯一的財產是彼此不同:

public IEnumerable<T> PopulateData() where T : class, new() 
{ 
    using (var conn = new SqlConnection(connection)) 
    { 
     conn.Open(); 

     using (var cmd = new SqlCommand(storedProcedureName, conn)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure; 

      using (var reader = cmd.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        var generic = new T() 
        { 
         // This will be filled with Username, Fullname, Email for FirstClass and add the Age for SecondClass and I confused about this part 
        }; 
        yield return generic; 
       } 
       reader.Close(); 
      } 
     } 
    } 
} 

而且我會這樣稱呼它:

PopulateData<FirstClass>(); 
PopulateData<SecondClass>(); 

但我想不出它是如何工作的。任何想法和幫助?

非常感謝。

+0

看實體框架 –

回答

0

假設DataReader中的列與您的類的成員匹配,或者您有某種映射,我想您可以使用反射來動態填充它們。

https://msdn.microsoft.com/en-us/library/6z33zd7h(v=vs.110).aspx

,因此會使用.SetValue在你聲明的generic對象設置的值,但你將不得不使用反射來獲取一個FieldInfo對象。所有這些都會有一些開銷,我相信很多像這樣的框架已經存在,所以在你走下去之前,你可能需要根據所取得的進展完全評估你的設計。 ORM和相關技術。

0

我一直在使用這種擴展方法與datatables很長一段時間了。您也可以將其更改爲使用IDataReader。只要datatable中的類屬性和列名相同,擴展方法就會將每個數據錶轉換爲對象的具體類列表。這裏是擴展方法

public static List<T> ToGenricList<T>(this DataTable table) where T : class, new() 
    { 
     try 
     { 
      List<T> list = new List<T>(); 

      foreach (var row in table.AsEnumerable()) 
      { 
       T obj = new T(); 

       foreach (var prop in obj.GetType().GetProperties()) 
       { 
        try 
        { 
         PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); 
         propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); 
        } 
        catch 
        { 
         continue; 
        } 
       } 

       list.Add(obj); 
      } 

      return list; 
     } 
     catch 
     { 
      return null; 
     } 
    } 

免責聲明:我從另一個計算器同胞這種方法,但我無法找到問題的鏈接現在

相關問題