转的,没有中文版,别怪我啊....

One of my friends called me after his interview for a developer role in an esteemed organization. One of the questions the interviewer asked him was:

What is Action in C#?

After talking to him, I thought why not blog about it? I am trying here to use a minimum of words and optimum code samples to discuss the answer of this interview question. 

An Action is a type of delegate:

  1. It returns no value.
  2. It may take 0 parameter to 16 parameters.

For example the following Action can encapsulate a method taking two integers as input parameters and returning void.

What is Action in C#?

So if you have a method like below:

What is Action in C#?

You can encapsulate the method Display in Action MyDelegate as below:

What is Action in C#?

An Action with one input parameter is defined in the System namespace as below:

What is Action in C#?

Where in T is a type of input parameter and a T object is a value passed for the parameter. 

Action with Anonymous method 

You can work with Action and anonymous methods as well. You can assign an anonymous method to an Action as below:

What is Action in C#?

The above code will print 9 as output. 

Action with Lambda Expression 

Like any other delegates, an Action can be created with a lambda expression also, as below:

What is Action in C#?

The above code will also print 9 as output. 

Passing Action as input parameter 

You can pass an Action as a parameter of a function also. Let us say you have a class:

What is Action in C#?

And two functions called Display and Show to display Name and RollNumber of Student. 

What is Action in C#?

Now you have a function where you need to pass either Display or Show. Or in other words you need to pass any function with the same signature of Display or Show. In that case you will be passing a delegate as an input parameter to the function. 

What is Action in C#?

You can call the CallingAction method in Main as below:

What is Action in C#?

Above we are creating an instance of the Student class and one by one passing to the Display function and the Show function as input parameter to the CallingAction function. In the CallingAction function, we are printing the name of the function being passed as input parameter. On running you will get the following output:

What is Action in C#?

I hope now you are able to answer what an Action is in simple words. I hope this post is useful. Thanks for reading. 


相关文章: