[英]one generic class create generic extension with expression<T,bool> method
我的代碼如下:
public partial class WhereHelper<T1> { }
public static partial class WhereHelperExtension
{
public static T Where<T,T1>(this T t, Expression<Func<T1,bool>> where) where T : WhereHelper<T1>
{
//do something....
return t;
}
}
public class Test
{
public void Main()
{
WhereHelper<DateTime> dt = new WhereHelper<DateTime>();
dt.Where(t => t.Year == 2016);//this is error
dt.Where<WhereHelper<DateTime>, DateTime>(t => t.Year == 2016);//this is success
}
}
擴展方法我想像這樣:
WhereHelper<DateTime> dt = new WhereHelper<DateTime>();
dt.Where(t => t.Year == 2016);//this is error
如何使用Expression方法創建通用擴展。 Visual Studio無法識別“ Where”擴展方法。
在C#中,如果您需要提供任何通用參數,則必須全部提供它們。 where
約束不提供線索的類型解析,所以它不可能決定什么T1
是。
將您的簽名更改為以下內容:
public static WhereHelper<T> Where<T>(this WhereHelper<T> t, Expression<Func<T,bool>> where)
{
return t;
}
在這里,我們僅從第一個參數確切地知道T
是什么,因此我們不必明確指定參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.