简体   繁体   中英

What does this c# syntax mean?

Hi I have a little problem with understanding this kind of syntax

public delegate void DelegateType();
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'只是一种东西,所以像任何其他类型一样,你想说“这是这种类型的一个实例”,你需要使用'new'。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM