【发布时间】:2016-02-18 10:24:46
【问题描述】:
我想使用 ToDataTable() 类将 List 转换为 DataTable。
问题是:类ToDataTable() 使用static 方法,它会出错。
我知道这个错误,但我不知道如何解决它。
错误代码为:Extension method must be defined in a non-generic static class
我使用的代码是:
var proxyInfos = proxyL
.Where(l => l.Contains(" US "))
.Select(l => l.Split(' '))
.Select(tokens => new
{
IP = tokens[0],
Port = tokens[1]
})
.ToList();
dtProxy = ToDataTable(proxyInfos);
以及将 List 转换为 DataTable 的类:
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
我在互联网上进行研究。比如,把我的班级改成静态的。
但我改成静态,错误继续出现:
Static class 'MyClass.MainForm' cannot derive from type 'System.Windows.Forms.Form'. Static classes must derive from object..
我的代码是这样的:
public static class MainForm : System.Windows.Forms.Form
{
}
【问题讨论】:
-
我认为你应该将这个方法 ToDataTable 移动到静态类中,并将其作为扩展方法。所以你可以简单地使用它,dtProxy = proxyInfos.ToDataTable();
标签: c#