我試圖創建一個通用的擴展方法,即在輸入數據表的工作原理:通用擴展方法:類型參數不能從使用推斷
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是這樣的'Expression <
Func <
T,bool>>
'將被鍵入並且被InteliSence看到。
感謝
我很害怕那個......謝謝你的回答 – 2010-09-02 19:14:59
你是對的:) – Brian 2010-09-02 21:43:38