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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With