C# 为什么可以';委托在静态方法中使用时是否引用非静态方法?

C# 为什么可以';委托在静态方法中使用时是否引用非静态方法?,c#,.net,visual-studio-2005,function,delegates,C#,.net,Visual Studio 2005,Function,Delegates,为什么在C#中使用委托时必须使函数保持静态 这不是“必要的”。但是您的主要方法是静态,因此它不能调用非静态方法。尝试这样的方法(这并不是一种很好的方法,您确实应该创建一个新类,但它不会对您的示例有太大的改变): 您的函数需要是静态的,因为您是从静态方法Main调用的。您可以将该方法设置为非静态: class Program { delegate int Fun (int a, int b); static void Main(string[] args) {

为什么在C#中使用委托时必须使函数保持静态

这不是“必要的”。但是您的主要方法是
静态
,因此它不能调用非
静态
方法。尝试这样的方法(这并不是一种很好的方法,您确实应该创建一个新类,但它不会对您的示例有太大的改变):


您的函数需要是静态的,因为您是从静态方法Main调用的。您可以将该方法设置为非静态:

class Program
{
    delegate int Fun (int a, int b);
    static void Main(string[] args)
    {
        Program p = new Program();       // create instance of Program
        Fun F1 = new Fun(p.Add);         // now your non-static method can be referenced
        int Res= F1(2,3);
        Console.WriteLine(Res);
    }

    public int Add(int a, int b)
    {
        int result;
        result = a + b;
        return result;
    }
}

在这种情况下,因为您没有创建任何类的实例,所以唯一的选择是静态函数。如果要实例化Program类型的对象,则可以使用实例方法。

委托基本上遵循与方法相同的规则。在提供的示例中,您的委托必须是静态的,因为您是从静态方法调用它的。同样,这也行不通:

static void Main(string[] args)
{
    int Res = Add(3, 4);
    Console.WriteLine(Res);
}

public int Add(int a, int b)
{
    int result;
    result = a + b;
    return result;
}
但是,如果您将内容移动到非静态上下文中,如下所示:

class MyClass
{
    public MyClass()
    {
        Fun F1 = new Fun(Add);
        int Res = F1(2, 3);
        Console.WriteLine(Res);
    }

    public int Add(int a, int b)
    {
        int result;
        result = a + b;
        return result;
    }
}

您可以使用非静态方法创建委托。

无需创建静态方法来传入委托

但是非静态方法应该在不同的类中声明,并且必须使用该类的实例来访问


DelegateName DN=new DelegateName(类的实例。方法名)

因为您试图从Main在静态上下文中引用它?我否认问题的前提;没有必要使该方法成为静态的。必须向委托人提供足够的信息以成功调用该方法;对于非静态方法,这包括提供接收非静态方法调用的实例。这不是真的,您可以从静态上下文委托给非静态方法。例如,MyDelegate del=foo.Bar;即使Bar不是静态的,并且赋值是在静态上下文中,也是有效的。很好地用代码反驳了您自己的声明。显然,Main(静态方法)通过调用它来引用Execute(实例方法)。正确的语句应该是“对于引用实例方法的静态方法或其他类的方法,它必须在这样做时提供实例”。同一类中的实例方法在引用实例方法时也必须提供实例(请检查IL以查看这一点),但C#编译器默认为“this”,因为您没有指定实例。
static void Main(string[] args)
{
    int Res = Add(3, 4);
    Console.WriteLine(Res);
}

public int Add(int a, int b)
{
    int result;
    result = a + b;
    return result;
}
class MyClass
{
    public MyClass()
    {
        Fun F1 = new Fun(Add);
        int Res = F1(2, 3);
        Console.WriteLine(Res);
    }

    public int Add(int a, int b)
    {
        int result;
        result = a + b;
        return result;
    }
}