ジェネリック メソッドを使用してジェネリック リストをデータテーブル/データセットに解析する方法について混乱しています。私のセットアップ: 1. WCF Service Library で定義された Customers クラスがあります。
namespace Wcf.Sample.ServiceLibrary
{
public class Customers
{
public string ID = string.Empty;
public string CompanyName = string.Empty;
public string ContactName = string.Empty;
}
}
2. このクラスを使用して、OperationContract からジェネリック リストを返します。
namespace Wcf.Sample.ServiceLibrary
{
[ServiceContract]
public interface ICustomerService
{
[OperationContract]
List<Customers> GetAllCustomers();
}
}
3. Web クライアント ページで WCF サービスを使用します。ボタンをクリックすると、GetAllCustomers() から返されたリストを GridView に入力します。これは完全に正常に機能します。
GridView1.DataSource = client.GetAllCustomers();
GridView1.DataBind();
4.問題は、何らかの理由(ソート/ページング機能)で、返されたジェネリックリストを実際にデータテーブルに変換したいということです。そのために、GridView にバインドするデータテーブルを返すメソッドがあります。メソッドは次のとおりです。
public static DataTable ConvertTo<T>(System.Collections.Generic.List<T> genericList)
{
//create DataTable Structure
DataTable dataTable = CreateTable<T>();
Type entType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in genericList)
{
DataRow row = dataTable.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
dataTable.Rows.Add(row);
}
return dataTable;
}
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable dataTable = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
dataTable.Columns.Add(prop.Name, prop.PropertyType);
}
return dataTable;
}
この関数を呼び出す方法がわかりませんか? 実際に Web サービスにある as Customers クラスを指定するにはどうすればよいですか? 完全に失われました。誰かが次のコード、それを機能させる方法について私を案内してくれれば幸いです。
GridView1.DataSource = ConvertTo<???>(client.GetAllCustomers());