How to 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 for F. I am trying this

public Func<T, T> FuncF = F;

      

but this is not syntactically correct. How can i do this.

+3


source to share


3 answers


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

      

+6


source


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

      

+1


source


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

      

+1


source







All Articles