c# - 为什么委托(delegate)在静态方法中使用时不能引用非静态方法?

标签 c# .net visual-studio-2005 function delegates

为什么在 C# 中使用委托(delegate)时需要将函数设为 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;
    }
}

最佳答案

这不是“必要的”。但是您的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; 
    } 
}

关于c# - 为什么委托(delegate)在静态方法中使用时不能引用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298997/

相关文章:

c# - 使用 C# Thread 删除文件

c# - 为什么.NET 中没有 IDateTimeProvider 而 DateTime 有 Now getter?

c# - 如何在传输过程中关闭请求流时获取 HTTP 响应

c# - 在 C# 中使用服务执行 psexec

visual-studio-2005 - 源安全,文件独占锁定

c# - 基于数组对列表进行排序

c# - 如何检查控件是否为按钮?

c# - 如何使用 ADO.NET 从具有一对多关系的 DAL 层中的多个表返回数据

.net - SplashScreen.Close() 窃取 MainWindow 的焦点

c++ - 变量值的后缀#DEN 是什么意思