C# 有没有办法>;公开无效测试<;A、 B,C,…,Z>;(...)

C# 有没有办法>;公开无效测试<;A、 B,C,…,Z>;(...),c#,C#,我尝试创建一种方法来构建快速数据表 我现在的代码是这样的 实施 var table = build("myTableName").col<int>("col1").col<string>("col2") .row(1, "row1") .row(2, "row2"); public static DataTable build(string name) { return new DataTable(name); } public static DataTable c

我尝试创建一种方法来构建快速数据表 我现在的代码是这样的

实施

var table = build("myTableName").col<int>("col1").col<string>("col2")
.row(1, "row1")
.row(2, "row2");

public static DataTable build(string name)
{
 return new DataTable(name);
}

public static DataTable col<T>(this DataTable table, string name)
{
 table.Columns.Add(colName, typeof(T));
 retun table;
}

public static DataTable row(this DataTable table, params object[] objects)
{
 DataRow row = table.NewRow();
 int i = 0;           
 objects.ToList().ForEach(obj => row[i++] = obj ?? DBNull.Value);
 table.Rows.Add(row);

 return table;
}
var table=build(“myTableName”).col(“col1”).col(“col2”)
.第(1)行,“第1行”)
。第(2)行,“第2行”);
公共静态数据表生成(字符串名称)
{
返回新的数据表(名称);
}
公共静态数据表列(此数据表,字符串名称)
{
表.Columns.Add(colName,typeof(T));
复床;
}
公共静态数据表行(此数据表,参数对象[]对象)
{
DataRow行=table.NewRow();
int i=0;
objects.ToList().ForEach(obj=>row[i++]=obj??DBNull.Value);
table.Rows.Add(行);
返回表;
}
如果有一种方法可以使用多个类型参数,我可以让事情变得更快。 比如

publicstaticcolcolcol(参数字符串[]名称){…}

实现这一点的唯一方法是为每一个参数创建一个重载,即一个
col
,一个
col
等等

NET框架也做了同样的事情。例如,
Func
有17个版本正是出于这个原因。

这应该可以:

public static DataTable col<T1>(this DataTable table, string name1)
{
    table.Columns.Add(name1, typeof(T1));
    return table;
}

public static DataTable col<T1, T2>(this DataTable table, string name1, string name2)
{
    table.Columns.Add(name1, typeof(T1));
    table.Columns.Add(name2, typeof(T2));
    return table;
}

public static DataTable col<T1, T2, T3>(this DataTable table, string name1, string name2, string name 3)
{
    table.Columns.Add(name1, typeof(T1));
    table.Columns.Add(name2, typeof(T2));
    table.Columns.Add(name3, typeof(T3));
    return table;
}

您可以创建多个类型参数,但必须为必须支持的每个列数创建一个显式重载


在我看来,这样做不是个好主意。它可能使您能够更快地编写这段代码,但我认为它会更难阅读。可读性很重要-代码的读取频率通常比编写频率高很多。

因为您只是在另一个方法调用中使用类型作为参数,这难道不起作用吗:

public static DataTable cols(this DataTable table, string[] names, Type[] types)
{
    for(...)
    {
        table.Columns.Add(names[i], types[i]); 
    }
    return table;
}

.cols(new string[] {"col1", "col2"}, new Type[] {typeof(int), typeof(string)})

不太好看,有很多方法可以改进“传递和迭代2个数组,希望它们大小相同”,但这是一般的想法。做一些检查,也许使用一个结构来传递数据,应该可以。

为什么给这个a-1?这是个好问题,谢谢。我过去经常听到这样的评论。我的同事常说我的日记很难读。但对我来说,我认为指定col()和row()比常规方法更具可读性。因为代码要短得多,所以更容易理解。。。。但我的同事不太同意我的看法:)
public static DataTable cols(this DataTable table, Type[] types, string[] names)
{
    // ...
}
public static DataTable cols(this DataTable table, string[] names, Type[] types)
{
    for(...)
    {
        table.Columns.Add(names[i], types[i]); 
    }
    return table;
}

.cols(new string[] {"col1", "col2"}, new Type[] {typeof(int), typeof(string)})