我对如何使用泛型方法将泛型列表解析为数据表/数据集感到困惑。我的设置: 1. 我在 WCF 服务库中定义了一个客户类。
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. 在网页客户端页面使用 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 服务中的客户类?完全迷失了。如果有人可以指导我使用以下代码以及如何使其工作,我将不胜感激。
GridView1.DataSource = ConvertTo<???>(client.GetAllCustomers());