Hi I have a little problem with understanding this kind of syntax
public delegate void Del开发者_JS百科egateType();
BeginInvoke(new DelegateType(functionName));
Could somebody tell me what exectly mean new DelegateType(functionName). Why do I have to use new keyword ??
See the documentation.
A delegate is a type that holds a method.
You're creating a new instance of a delegate type, pointing to an existing method.
C# 2 adds an implicit conversion from a method group to any matching delegate type.
However, since BeginInvoke
doesn't take a specific delegate type (such as System.Action
), you always need to explicitly create a delegate instance.
The first statement declares a delegate type, the second statement instantiates a new delegate of DelegateType
.
From the corresponding MSDN article (read the article for more information!):
Once a delegate type has been declared, a delegate object must be created and associated with a particular method. Like all other objects, a new delegate object is created with a new expression. When creating a delegate, however, the argument passed to the new expression is special — it is written like a method call, but without the arguments to the method.
public delegate void DelegateType();
This defines the syntax for a delegate. This is a reference to a method, either static, or an instance method.
When you call BeginInvoke, you're passing a delegate as the parameter. The C# compiler will convert from any explicit delegate type to System.Delegate, but since the parameter is defined as taking any delegate (via System.Delegate), you must explicitly define the type.
When you specify:
new DelegateType(functionName)
You're creating a delegate of a specific type (DelegateType), which is then passed to the function.
Often, newer APIs will use a known type, such as System.Action (which has the same syntax as your DelegateType). If a method takes an "Action", you would not need the definition above, and you could do:
CallMethodTakingAction(functionName);
'DelegateType' is only a type of thing, so like any other type, you want to say "here's one instance of this type", you need to use 'new'.
精彩评论