为什么委托在静态方法中使用时不能引用非静态方法?

Sun*_*has 7 .net c# delegates visual-studio-2005 function

为什么在C#中使用委托时需要使用STATIC函数?

class Program
{
    delegate int Fun (int a, int b);
    static void Main(string[] args)
    {
        Fun F1 = new Fun(Add);
        int Res= F1(2,3);
        Console.WriteLine(Res);
    }

   **static public int Add(int a, int b)** 
    {
        int result;
        result = a + b;
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ðаn*_*Ðаn 12

这不是必需的".但是你的Main方法是static,所以它不能调用非static方法.尝试这样的事情(这不是一个很好的做事方式 - 你真的应该创建一个新的类,但它不会更改你的样本):

class Program 
{ 
    delegate int Fun (int a, int b); 
    void Execute()
    {
       Fun F1 = new Fun(Add); 
       int Res= F1(2,3); 
       Console.WriteLine(Res); 
    }

    static void Main(string[] args) 
    { 
        var program = new Program();
        program.Execute();
    } 

    int Add(int a, int b)
    { 
        int result; 
        result = a + b; 
        return result; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • 干得好用你的代码反驳自己的主张.显然,Main(静态方法)通过调用它来引用Execute(实例方法).正确的语句是"对于另一个类的静态方法或方法来引用实例方法,它必须在执行时提供实例".同一类中的实例方法在引用实例方法时也必须提供实例(请检查IL以查看此内容),但C#编译器默认为"this"是您未指定的方法. (3认同)

Amy*_*Amy 8

你的函数需要是静态的,因为你是从静态方法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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @pdr:?? 问题是为什么该方法必须是静态的.我的答案是它不一定是,并且证明了它. (2认同)