C# 如何创建泛型Func委托

C# 如何创建泛型Func委托,c#,.net,delegates,func,C#,.net,Delegates,Func,我有这个方法 public static T F<T>(T arg) { return arg; } 公共静态tf(T arg) { 返回arg; } 我想创建一个F的Func委托。我试试这个 public Func<T, T> FuncF = F; public Func Func=F; 但它在语法上是不正确的。如何做到这一点。只有类和方法本身才是泛型的。使用泛型参数的字段必须位于泛型类上下文中: public class

我有这个方法

    public static T F<T>(T arg)
    {
        return arg;
    }
公共静态tf(T arg)
{
返回arg;
}
我想创建一个F的Func委托。我试试这个

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

但它在语法上是不正确的。如何做到这一点。

只有类和方法本身才是泛型的。使用泛型参数的字段必须位于泛型类上下文中:

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

    public Func<T, T> FuncF = F;
}
F
是一种可分配给
Func
变量的方法

F
是一种不同的方法,可分配给
Func
变量

但是不能有泛型变量。C#就是不能那样工作

最接近泛型变量的是泛型类的字段:

static class DelegateContainer<T>
{
  public static Func<T, T> FuncF = F;
}
静态类DelegateContainer
{
公共静态Func FuncF=F;
}
您只能(重新)公开泛型类或泛型方法中的泛型。否则,您需要为
T
提供明确的类型(例如,对于局部变量或作为非泛型类中的字段或属性)。示例:

// 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
    }
}
//即通过将Func包装在静态类中重新公开:
公共静态类MyFuncs
{
公共静态TF(T参数)
{
返回arg;
}
}
公共类泛型
{
//将其用作字段
私有函数f=MyFuncs.f;
//或getter func
公共职能
{
返回MyFuncs.F;
}
}
//通过泛型方法重新公开泛型
公共类泛型方法
{
公共职能
{
返回MyFuncs.F;
}
}
//也就是说,使用泛型,不要重新公开
公共类特定类
{
公共食物功能(食物功能)
{
return MyFuncs.F(F);//是可选的-编译器可以推断
}
}

对我来说似乎不错@dcastro您添加了一些不在原始问题中的内容,这就是它工作的原因。@DStanley我假设封闭类是泛型的:/I我假设太多了
// 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
    }
}