-3

命名空间 DelegatePractise1 {

public delegate int AddDelegate(int x, int y);

class Calculator
{
    MathOps opsObj = new MathOps();
    static void Main(string[] args)
    {

        AddDelegate addDelInstance = new AddDelegate(opsObj.Add);//getting error here 
        int sum = addDelInstance(2, 3);
        Console.WriteLine("{0} sum", sum);
        Console.Read();

    }
}

public class MathOps
{
     public int Add(int x, int y)
    {
        return x + y;
    }
}

}

当我在 main 中初始化对象“opsObj”时,错误不再出现。你能解释一下为什么我需要在这种情况下在 main 中包含对象初始化吗?我是 oop 概念的新手。提前致谢

4

2 回答 2

0

您不能在静态主方法中使用非静态对象,因此将其转换为静态以使其工作或添加具有所有逻辑的新类,这将解决问题

static MathOps opsObj = new MathOps();
于 2019-11-17T05:51:41.960 回答
-1

您可以像这样简单地分配委托:

 AddDelegate addDelInstance = opsObj.Add;
于 2019-11-17T05:51:41.710 回答