gpt4 book ai didi

c# - 如何在 C# 中使用带有静态方法的类?

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:27 24 4
gpt4 key购买 nike

我想使用类 ToDataTable() 将 List 转换为 DataTable。问题是:使用 static 方法的 ToDataTable() 类会出错。我知道这个错误,但我不知道如何解决。

错误代码为:必须在非泛型静态类中定义扩展方法

我使用的代码是:

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;
}

我正在互联网上进行研究。比如,将我的类(class)更改为静态。但我改为静态,错误继续出现:静态类“MyClass.MainForm”不能派生自类型“System.Windows.Forms.Form”。静态类必须派生自对象。

我的代码是这样的:

public static class MainForm : System.Windows.Forms.Form
{
}

最佳答案

只需删除this

public static DataTable ToDataTable<T>(IList<T> data)

并作为简单的静态方法使用

或者将这个函数移动到单独的静态

喜欢

public static class UnilityExtensions
{
public static DataTable ToDataTable<T>(this IList<T> data)
{ ... }
}

关于c# - 如何在 C# 中使用带有静态方法的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35478779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com