简体   繁体   中英

one generic class create generic extension with expression<T,bool> method

My code is as follows:

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
    }
}

Extension method I want to be like this:

WhereHelper<DateTime> dt = new WhereHelper<DateTime>();
dt.Where(t => t.Year == 2016);//this is error

how to create generic extension with Expression method. Visual Studio does not recognize the "Where" extension methods.

In C#, if you need to provide any generic argument, you must provide them all. where constraints do not provide hints to the type resolver, and so it's impossible to decide what T1 is.

Change your signature to the following:

public static WhereHelper<T> Where<T>(this WhereHelper<T> t, Expression<Func<T,bool>> where)
{
    return t;
}

Here, we know exactly what T , purely from the first argument, and so we do not have to explicitly specific the arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM