简体   繁体   中英

Is it possible to create a generic Func<T><T>

Is it possible to create a generic Func<T><T> , as in a Func that accepts a generic parameter and needs to return the type of that generic parameter?

In other words, can I do this?

Func<T> createNull = () => default(T);

Note that I don't have any context from a containing class or method, so I'd want to do:

var user = createNull<User>();

Here's a bit more info about what I'm trying to do.(note that the syntax is off, because I don't know how to do it nor whether it's possible):

Func<TQuery, TResult><TQuery, TResult> query = q => 
    (TResult) handlers[Tuple.Create(typeof(TQuery), typeof(TResult))](q);

where handlers is declared as following:

var handlers = new Dictionary<Tuple<Type, Type>, Func<TQuery, TResult><TQuery, TResult>();
// examples
handlers.Add(Tuple.Create(typeof(ById), typeof(User)), 
             idQuery => new User());
handlers.Add(Tuple.Create(typeof(ByName), typeof(Customer)), 
             otherQuery => new Customer());

Then I'd like to use query like this:

User result = query<User, IdQuery>(new ById{Id = 1});
Customer result1 = query<Customer, ByName>(new ByName());

No, but you can put it in static class that will give you almost what you want:

static class CreateNull<T>
{
   public static Func<T> Default = () => default(T);
}

var createNull = CreateNull<User>.Default;

No. Generics can be applied to methods, delegates and classes only.

Generics are a compiler feature that allow you to write one method and the compiler will generate a method for each set of types required. So if you write:

public T DoSomething<T>(T input)

and then use it:

int result1 = DoSomething(1);
double result2 = DoSomething(2.0);
MyType result3 = DoSomething(new MyType());

For each of the lines above the JIT generates a new overload of the method.

Lambdas are typed, so they generate a specific overload of the delegate in question:

// Given generic Func<TInput, TResult>
Func<int, string> foo = (s) => Integer.parseInt(s);

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