【发布时间】:2011-04-07 12:09:48
【问题描述】:
我正在尝试创建一个适用于类型化数据表的通用扩展方法:
public static class Extensions
{
public static TableType DoSomething<TableType, RowType>(this TableType table, param Expression<Func<RowType, bool>>[] predicates)
where TableType : TypedTableBase<RowType>
where RowType : DataRow
{
// do something to each row of the table where the row matches the predicates
return table;
}
[STAThread]
public static void main()
{
MyTypedDataSet.MyTypedDataTable table = getDefaultTable();
}
public static MyTypedDataSet.MyTypedDataTable getDefaultTable()
{
// this line compiles fine and does what I want:
return new MyTypedDataSet.MyTypedDataTable().DoSomething<MyTypedDataSet.MyTypedDataTable, MyTypedDataSet.MyTypedRow>(row => row.Field1 == "foo");
// this line doesn't compile :
return new MyTypedDataSet.MyTypedDataTable().DoSomething(row => row.Field1 == "foo");
// Error : The type arguments .. cannot be inferred from the usage
}
}
第一行效果很好,但真的很难看...
第二行无法编译,因为编译器无法推断 RowType 的类型。
这个方法将被许多不同的程序员用作 DataLayer 的一部分,所以我宁愿不需要他们指定 TypeParameter。
编译器不应该知道 RowType 与 TypedTableBase 使用的类型相同吗?
由于在此代码示例中可能不明显的不同原因,我确实需要以原始形式返回数据表。我需要 RowType 的原因是 InteliSence 将输入并看到“Expression<Func<T, bool>>”。
谢谢
【问题讨论】:
标签: c# database generics lambda