开发者

Why can't a delegate refer to a non-static method when used in a static method?

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 Ad开发者_JAVA技巧d(int a, int b)** 
    {
        int result;
        result = a + b;
        return result;
    }
}


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


Your function needs to be static because you're calling from a static method, Main. You can make the method non-static:

class Program
{
    delegate int Fun (int a, int b);
    static void Main(string[] args)
    {
        Program p = new Program();       // create instance of Program
        Fun F1 = new Fun(p.Add);         // now your non-static method can be referenced
        int Res= F1(2,3);
        Console.WriteLine(Res);
    }

    public int Add(int a, int b)
    {
        int result;
        result = a + b;
        return result;
    }
}


In this case, because you aren't creating an instance of any class, the only alternative is a static function. Were you to instantiate an object of type Program, then you could use an instance method instead.


Delegates basically follow the same rules as methods. In the example provided your delegate must be static because you are calling it from a static method. In the same vein this will not work:

static void Main(string[] args)
{
    int Res = Add(3, 4);
    Console.WriteLine(Res);
}

public int Add(int a, int b)
{
    int result;
    result = a + b;
    return result;
}

However if you moved things into a non static context like this:

class MyClass
{
    public MyClass()
    {
        Fun F1 = new Fun(Add);
        int Res = F1(2, 3);
        Console.WriteLine(Res);
    }

    public int Add(int a, int b)
    {
        int result;
        result = a + b;
        return result;
    }
}

You can have a delegate with a non-static method.


No need to create a static method to pass in delegate.

But the non static method should be declared in different class and have to be accessed with instance of that class.

DelegateName DN = new DelegateName ( instance of the class . Method Name)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜