[英]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.