Was delegates static 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 开发者_JAVA百科:" + subRes);
I didn't declare delegate to be static but i was able to access it using the Class name. How is it possible?
You're not declaring a variable but a new delegate type named MyDelegate
in the class. As this is a type declaration static and instance doesn't really apply. In your main method you declare an actual variable of that type. Similarly, you could have created both instance and static members of the type MyDelegate
on the class.
Inner classes (& enums & delegates) do not need a class instance to be referred to. You can think of it more like a sort of namespace rather than a member.
If you are comparing C# to java, then I think all inner types count as "static" in the java sense - They have access to their outer classes privates but they'd need a reference to the outer class first.
In your example, Mydelegate is actually a nested type inside of delegatesEx. Nested types aren't associated with any particular instance of the outer class. When you declare it like this, you're basically just using the outer class as a kind of namespace. If you just moved this line outside of the class definition, your application would function identically.
public delegate int Mydelegate(int first, int second);
And change your references from delegatesEx.Mydelegate to just Mydelegate.
Mydelegate myAddDelegates = new Mydelegate(new delegatesEx().add);
Mydelegate mySubDelegates = new Mydelegate(new delegatesEx().sub);
+1 to Brian. Adding on a code snippet to his answer.
You're not declaring a class member - instead you're defining a new nested type. See the code sample below... defining a nested delegate is creating a new nested type (like a nested class) which derives from MultiCastDelegate.
The only access modifiers that matter are in front of the nested type - e.g. If you mark the delegate as Private, you can't create outside of 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();
精彩评论