Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a generic Func delegate

I have this method

    public static T F<T>(T arg)
    {
        return arg;
    }

and I want to create a Func delegate to F. I try this

public Func<T, T> FuncF = F;

but it's not syntactically correct. How I can do that.

like image 762
Alexander Leyva Caro Avatar asked Nov 05 '14 13:11

Alexander Leyva Caro


People also ask

How do you define generic delegates?

You can define a Generic delegate with type parameters. delegate T numbermanipulat<T>(T var); T is the generic type parameter that allows you to specify an arbitrary type (T) to a method at compile time without specifying a collection type in the method or class declaration.

Can delegates be used with generic types?

Delegates defined within a generic class can use the generic class type parameters in the same way that class methods do. Generic delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.

How do you assign a delegate to a function?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.

What is a Func delegate?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.


1 Answers

Only classes and methods can be generic in and of themselves. A field that uses generic parameters must be within a generic class context:

public class Test<T>
{
    public static T F(T arg)
    {
        return arg;
    }

    public Func<T, T> FuncF = F;
}

Or if the type parameter for F should not be connected to FuncF, then just use a different name for one of the parameters:

public class Test<T>
{
    public static U F<U>(U arg)
    {
        return arg;
    }

    public Func<T, T> FuncF = F;
}
like image 164
D Stanley Avatar answered Oct 22 '22 03:10

D Stanley