简体   繁体   中英

Action delegate -declaration correction

According to the definition of action delegate it does not return value but passes value.

I pass the value to Console.WriteLine( )

Action<int> an = new Action<int>(Console.WriteLine(3000));

But still i receive error as method name expected.What is the problem?

The constructor of Action<int> expects you to pass a pointer to a function that takes an integer as parameter and returns nothing. What you are passing is not a function but an expression. You could either define an anonymous function or use an existing one:

Action<int> an = new Action<int>(t => Console.WriteLine(t));
an(3000);

You would code it like this:

Action<int> an = new Action<int>(Console.WriteLine);
an(3000);

Chris

Action points to a method only not to any parameters.

You can then use it like this to invoke the action:

Action<int> action = new Action<int>(Console.WriteLine);
action.Invoke(3000);

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