Were there static delegates by default?

I was just trying to understand delegates using the following code.

public class delegatesEx
{
    public delegate int Mydelegate(int first, int second);

    public int add(int first, int second)
    {
        return first + second;
    }
    public int sub(int first, int second)
    {
        return first - second;
    }
}

Here is my main method

Console.WriteLine("******** Delegates ************");
delegatesEx.Mydelegate myAddDelegates = new delegatesEx.Mydelegate(new delegatesEx().add);
int addRes = myAddDelegates(3, 2);
Console.WriteLine("Add :" + addRes);

delegatesEx.Mydelegate mySubDelegates = new delegatesEx.Mydelegate(new delegatesEx().sub);
int subRes = mySubDelegates(3, 2);
Console.WriteLine("Sub :" + subRes);

I did not declare that the delegate is static, but I was able to access it using the class name. How is this possible?

+3
source share
4 answers

You are not declaring a variable, but a new delegate type with a name MyDelegatein the class. Since this is a static declaration, the instance is not actually applied. In the main method, you declare a valid variable of this type. Similarly, you could create both an instance and static type members MyDelegatein a class.

+5
source

Mydelegate Ex. - . , . , .

public delegate int Mydelegate(int first, int second);

Ex.Mydelegate Mydelegate.

Mydelegate myAddDelegates = new Mydelegate(new delegatesEx().add);
Mydelegate mySubDelegates = new Mydelegate(new delegatesEx().sub);
+3

(& ) , . , .

# java, , "" java. , .

+1

+1 . .

You do not declare a member of the class; instead, you define a new nested type. See Code Example below ... defining a nested delegate creates a new nested type (for example, a nested class) that derives from MultiCastDelegate.

The only access modifiers that matter are in front of the nested type - for example. If you mark a delegate as Private, you cannot create outside the containing type.

class A 
{
  public delegate void DoSomethingWithAnInt(int x);
  public class InnerA
  {
    public void Boo() 
    { Console.WriteLine("Boo!"); }
  }
}

client func ()

var del = new A.DoSomethingWithAnInt(Print);
del.Invoke(10);

var obj = new A.InnerA();
obj.Boo();
+1
source

Source: https://habr.com/ru/post/1741038/


All Articles