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

栏目: ASP.NET · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/2298997/why-cant-a-delegate-refer-to-a-non-static-method-when-used-in-a-static-method
为什么在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;
    }
}
这不是必需的”.但是你的Main方法是静态的,所以它不能调用非静态方法.尝试这样的事情(这不是一个很好的做事方式 – 你真的应该创建一个新类,但它不会改变你的样本):
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; 
    } 
}

翻译自:https://stackoverflow.com/questions/2298997/why-cant-a-delegate-refer-to-a-non-static-method-when-used-in-a-static-method


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Distributed Systems

Distributed Systems

Sukumar Ghosh / Chapman and Hall/CRC / 2014-7-14 / USD 119.95

Distributed Systems: An Algorithmic Approach, Second Edition provides a balanced and straightforward treatment of the underlying theory and practical applications of distributed computing. As in the p......一起来看看 《Distributed Systems》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试