2011-12-29 27 views
0

如何從類名(它作爲參數傳遞)動態創建列表並返回列表在C#中。如何從類名(它作爲參數傳遞)動態創建列表並返回c#中的列表.net

下面的代碼可能不起作用。我已發佈它給出一個想法:

public T ConvertDataSetToList<T>(DataSet _ds, String tableName, string className) 
    { 
     Type classType=Type.GetType(className); 
     List<T> newList = new List<T>(); 

     //System.Activator.CreateInstance(Type.GetType(className)); 

     try 
     { 
      Details _Details; 
      for (int iRowCount = 0; iRowCount < _ds.Tables[tableName].Rows.Count; iRowCount++) 
      { 
       _Details = FillDTO(_ds.Tables[tableName].Rows[iRowCount]); 
       newList.Add(_msDetails); 
      } 
     } 
     catch (Exception ex) { } 
     return newList; 
    } 
+0

我想基本上做的是轉換數據集列出並與數據集,類名和表名作爲參數,返回列表。如果上述想法不好,請提供其他可行的解決方案。 – user1107973 2011-12-29 07:49:53

回答

0

你可以用一些基本的映射東西。

//Maps a dataset 
public List<T> MapDataSet<T>(DataSet anyDataset 
          , string tablename) where T : new() 
{ 
    return MapDataTable<T>(anyDataset.Tables[tablename]); 
} 

// Maps a datatable 
public List<T> MapDataTable<T>(DataTable table) where T : new() 
{ 
    List<T> result = new List<T>(); 
    foreach(DataRow row in table.Rows) 
    { 
    result.Add(MapDataRow<T>(row)); 
    } 
    return result; 
} 

// maps a DataRow to an arbitrary class (rudimentary) 
public T MapDataRow<T>(DataRow row) where T: new() 
{ 
    // we map columns to class properties 
    Type destinationType = typeof(T); 
    // create our new class 
    T mappedTo = new T(); 
    // iterate over the columns 
    for(int columnIndex=0;columnIndex<row.ItemArray.Length;columnIndex++) 
    { 
    // get a matching property of our class 
    PropertyInfo fieldTo = destinationType.GetProperty(
           row.Table.Columns[columnIndex].ColumnName); 
    if (fieldTo !=null) 
    { 
     // map our fieldvalue to our property 
     fieldTo.SetValue(mappedTo, row[columnIndex], new object[] {}); 
    } 
    else 
    { 
    // sorry, field doens't match any property on class 
    } 
    } 
    return mappedTo; 
} 

這是基本的測試程序來證明其使用

void Main() 
{ 
    DataTable dt = new DataTable("hello"); 
    dt.Columns.Add("foo"); 
    dt.Columns.Add("bar"); 
    dt.Columns.Add("foobar"); 

    DataRow row = dt.NewRow(); 
    row[0]="blah1"; 
    row[1] ="two"; 
    row[2] = "fb1"; 

    dt.Rows.Add(row); 

    row = dt.NewRow(); 
    row[0]="apples"; 
    row[1] ="pears"; 
    row[2] = "duh"; 

    dt.Rows.Add(row); 

    List<DTO> list = MapDataTable<DTO>(dt); 
    List<SecondDTO> list2 = MapDataTable<SecondDTO>(dt); 

} 

// sample DTO object 
public class DTO 
{ 
    public string foo { get; set;} 
    public string bar { get; set; } 
} 

// another sample DTO object 
public class SecondDTO 
{ 
    public string foo { get; set;} 
    public string foobar { get; set; } 
} 
相關問題