How to create a generic Func delegate
Only classes and methods can be shared by themselves. A field that uses shared parameters must be in the general context of the class:
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
shouldn't be connected to FuncF
, 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;
}
source to share
F<int>
is a method that is assigned to a variable Func<int, int>
.
F<double>
is another method that is assigned to a variable Func<double, double>
.
But you cannot have shared variables. C # just doesn't work.
The closest thing to shared variables is a generic class field:
static class DelegateContainer<T>
{
public static Func<T, T> FuncF = F;
}
source to share
You can only (re) expose generics from a generic class or a generic method. Otherwise, you will need to specify specific types for T
(for example, for a local variable, or as fields or properties in a non-equivalent class). Examples:
// I.e. Re-expose by wrapping your Func in a static class:
public static class MyFuncs
{
public static T F<T>(T arg)
{
return arg;
}
}
public class Generics<T>
{
// Use it as a field
private Func<T, T> f = MyFuncs.F;
// Or getter func
public Func<T, T> FuncF()
{
return MyFuncs.F;
}
}
// Re-expose generic via Generic Method
public class GenericMethod
{
public Func<T, T> FuncF<T>()
{
return MyFuncs.F;
}
}
// i.e. Consume the generic and do not re-expose it
public class SpecificClass
{
public Foo FuncF(Foo f)
{
return MyFuncs.F<Foo>(f); // <Foo> is optional - compiler can infer
}
}
source to share