[英]Func type with a parameter and void return
I wanted to know why this doesn't work ?我想知道为什么这不起作用? The compiler says that void cannot be used with
Func
type.编译器说 void 不能与
Func
类型一起使用。 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. Func<T, TResult>
委托有一个参数并返回TResult
指定类型的值,您不能使用void
,因为它指定该方法不返回任何值并且不能用作类型参数。
You can use Action<T>
delegate in your example, it has a single parameter and doesn't return a value您可以在示例中使用
Action<T>
委托,它只有一个参数并且不返回值
Action<int> action = (x) => { Console.WriteLine("Hello World"); };
Since x
parameter isn't used, you can just use parameterless Action
delegate由于未使用
x
参数,您可以只使用无参数的Action
委托
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.您可以声明一个
Action
,但可以通过返回例如一个空对象来克服这个问题。
Func<int,object> func1 = (x) => { Console.WriteLine("Hello World"); return null;};
func1(2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.