Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法访问调用代理?_C#_.net_Delegates - Fatal编程技术网

C# 无法访问调用代理?

C# 无法访问调用代理?,c#,.net,delegates,C#,.net,Delegates,这将输出上述7和12的结果 在当前状态下,无法从main直接调用委托函数 为什么不能从主视图中看到代理 是否需要创建一个类 如何调用委托函数 您根本不调用该方法,现在也不能调用,因为Main方法是静态的,而您的方法不是静态的 我建议将您的代码拆分为第二个类,这更容易调用。(而不是使所有方法都是静态的) 然后,在Main方法中,实例化Assignment类的一个实例,并调用UseDelegate: public class Assignment { /* all code except the M

这将输出上述7和12的结果

在当前状态下,无法从main直接调用委托函数

  • 为什么不能从主视图中看到代理
  • 是否需要创建一个类
  • 如何调用委托函数

  • 您根本不调用该方法,现在也不能调用,因为
    Main
    方法是静态的,而您的方法不是静态的

    我建议将您的代码拆分为第二个类,这更容易调用。(而不是使所有方法都是静态的)

    然后,在
    Main
    方法中,实例化
    Assignment
    类的一个实例,并调用
    UseDelegate

    public class Assignment
    { /* all code except the Main method goes here */ }
    

    不能从静态方法调用非静态方法,因此必须实现另一个类,如

    public static void Main()
    {
        Assignment a = new Assignment();
        a.UseDelegate();
    
        Console.ReadKey(); // to prevent the console from closing immediate
    }
    
    您可以从主方法调用它,如

    internal class Check
    {
        public delegate int Calculate(int x, int y);
    
        public int Add(int x, int y)
        {
            return x + y;
        }
    
        public int Multiply(int x, int y)
        {
            return x * y;
        }
    
        public void UseDelegate()
        {
            Calculate calc = Add;
            Console.WriteLine(calc(3, 4)); //Displays 7
    
            calc = Multiply;
            Console.WriteLine(calc(3, 4));//Displays 12
        }
    }
    
    internal class Check
    {
        public delegate int Calculate(int x, int y);
    
        public int Add(int x, int y)
        {
            return x + y;
        }
    
        public int Multiply(int x, int y)
        {
            return x * y;
        }
    
        public void UseDelegate()
        {
            Calculate calc = Add;
            Console.WriteLine(calc(3, 4)); //Displays 7
    
            calc = Multiply;
            Console.WriteLine(calc(3, 4));//Displays 12
        }
    }
    
     private static void Main(string[] args)
            {
                new Check().UseDelegate();
            }