无法使用var和foreach将void分配给隐式类型的局部变量 [英] Cannot assign void to an implicitly-typed local variable with var and foreach
问题描述
我试图列出表单中所有按钮的名称,并用代码列出
I'm trying to list all buttons name from my form to list with code
var v = new List<Form1>() { this }.ForEach(x => { x.GetType().Name.Contains(typeof(Button).Name); });
总是出错
不能将void分配给隐式类型的局部变量
Cannot assign void to an implicitly-typed local variable
如何绕开它?
推荐答案
Foreach
返回void
,这就是您收到错误的原因.您在作业右侧的陈述不返回任何内容.您可以在两条语句中执行相同的操作,例如:
Foreach
returns void
that is why you are getting the error. Your statement on the right hand side of assignment is not returning anything. You can do the same in two statements like:
var v = new List<Form1>() { this };
v.ForEach(x => { x.GetType().Name.Contains(typeof(Button).Name); });
在当前代码中,您正在创建一个新的List<Form1>
,然后遍历列表中的每个项目,但是您未返回任何内容.
In your current code you are creating a new List<Form1>
and then iterating over each item in the list, but you are not returning anything.
正如乔恩·斯基特(Jon Skeet)在评论中指出的那样,它对列表没有任何影响.我想您正在尝试从表单列表中获取所有按钮:
As Jon Skeet has pointed out in the comment, it will not have any effect on the list. I guess you are trying to get all the button from your list of forms you can do:
var allButtons = v.SelectMany(r => r.Controls.OfType<Button>()).ToList();
这篇关于无法使用var和foreach将void分配给隐式类型的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!