为什么委托在静态方法中使用时不能引用非静态方法? [英] Why can't a delegate refer to a non-static method when used in a static method?

查看:22
本文介绍了为什么委托在静态方法中使用时不能引用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is it necessary to make a function STATIC while using delegates in C# ?

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 方法.尝试这样的事情(这不是一个真正的好方法——你确实应该创建一个新类,但它不会对你的示例有太大的改变):

It's not "necessary". But your Main method is static, so it can't call a non-static method. Try something like this (this isn't really a good way to do things—you really should create a new class, but it doesn't change your sample much):

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; 
    } 
}

这篇关于为什么委托在静态方法中使用时不能引用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆