简体   繁体   English

无法使用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); });

and always get error 总是出错

Cannot assign void to an implicitly-typed local variable 无法将void分配给隐式类型的局部变量

How to bypass that? 如何绕开呢?

Foreach returns void that is why you are getting the error. Foreach返回void ,这就是您收到错误的原因。 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); });

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. 在您当前的代码中,您正在创建一个新的List<Form1> ,然后遍历列表中的每个项目,但是您未返回任何内容。

As Jon Skeet has pointed out in the comment, it will not have any effect on the list. 正如乔恩·斯基特(Jon Skeet)在评论中指出的那样,它对列表没有任何影响。 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();

I suspect you're really looking for Where - just calling Contains in a ForEach call isn't going to do anything for you. 我怀疑你真的找Where -只是调用ContainsForEach通话是不会为你做任何事情。 Likewise I don't think you're really looking for a list of forms if you're interested in buttons . 同样,如果您对按钮感兴趣,我也不认为您真的在寻找表单列表。 I suspect you may be looking for: 我怀疑您可能正在寻找:

var buttons = this.Controls.OfType<Button>().ToList();

Note that this won't go into nested controls - if you need to do that, you'll need something recursive. 请注意,这不会进入嵌套控件-如果您需要这样做,则将需要递归操作。 (You may well be able to find other questions asking for that... it doesn't help that we don't know whether this is WinForms, WebForms, something else...) (您也许能够找到其他要求的问题……我们不知道这是WinForms,WebForms还是其他东西,这无济于事。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM