I wanted to know why this doesn't work ? The compiler says that void cannot be used with Func
type. In that case what are my options
Func<int,void> func1 = (x) => { Console.WriteLine("Hello World"); };
Func<T, TResult>
delegate has one parameter and returns a value of the type specified by TResult
, you can't use void
, because it specifies that method doesn't return any value and can't be used as type argument.
You can use Action<T>
delegate in your example, it has a single parameter and doesn't return a value
Action<int> action = (x) => { Console.WriteLine("Hello World"); };
Since x
parameter isn't used, you can just use parameterless Action
delegate
Action action = delegate { Console.WriteLine("Hello World"); };
您正在寻找Action<int>
You can declare an Action
, but the problem can be overcome by returning for example a null object.
Func<int,object> func1 = (x) => { Console.WriteLine("Hello World"); return null;};
func1(2);
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.