我的代码如下:
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
从第一个参数中确切知道了什么,因此我们不必显式地指定参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句