是否有与 C 的逗号运算符等效的惯用 C#? [英] Is there idiomatic C# equivalent to C's comma operator?
问题描述
我在 C# 中使用了一些函数式的东西,并且一直被 List.Add
不返回更新列表的事实所困扰.
I'm using some functional stuff in C# and keep getting stuck on the fact that List.Add
doesn't return the updated list.
一般来说,我想在一个对象上调用一个函数,然后返回更新后的对象.
In general, I'd like to call a function on an object and then return the updated object.
例如,如果 C# 有一个逗号运算符就好了:
For example it would be great if C# had a comma operator:
((accum, data) => accum.Add(data), accum)
我可以像这样编写自己的逗号运算符":
I could write my own "comma operator" like this:
static T comma(Action a, Func<T> result) {
a();
return result();
}
看起来它可以工作,但呼叫站点会很难看.我的第一个例子是这样的:
It looks like it would work but the call site would ugly. My first example would be something like:
((accum, data) => comma(accum.Add(data), ()=>accum))
足够的例子!如果没有其他开发人员稍后出现并对代码气味皱眉,那么最干净的方法是什么?
Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?
推荐答案
使用 C# 3.0 中的代码块,您几乎可以自然地完成第一个示例.
You can do almost exactly the first example naturally using code blocks in C# 3.0.
((accum, data) => { accum.Add(data); return accum; })
这篇关于是否有与 C 的逗号运算符等效的惯用 C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!