C# 中的运算符重载
我昨晚在写 if 表达式时突然有了一个想法 有时,当你有这样的表达式时,表达式往往会很长:
if(x == 1 || x == 2 || x == 33 || x == 4 || x == -5 || x == 61) { ... }
x可以是枚举、字符串、整数、字符,你就明白了。
我想知道是否有更简单的写法。 例如,我认为 sql 的运算符 'in' 是一种缩短表达式的简便方法:
if(x in (1,2,33,4,-5,61)) { ... }
我知道你不能用 'in' 编写这样的表达式,因为编译器的词法分析器和解析器无法识别它。
也许其他解决方案作为不同类型 x 的扩展方法是解决方案? 在即将到来的 .NET 4.0 中,我听说了一些有关参数化方法的内容,这是否应该解决提供给 if 表达式的 n 个参数数量?
也许您理解我,您对这个问题有一个好的实践/解决方案的想法吗?
/丹尼尔
I just had an idea last nigth when writing an if-expression
and sometimes the expression tend to be long when you have it like this:
if(x == 1 || x == 2 || x == 33 || x == 4 || x == -5 || x == 61) { ... }
x can be enums,strings,ints,chars you get the picture.
I want to know if there are an easier way of writing this.
I think of sql's operator 'in' for example as a eay to shorten the expression:
if(x in (1,2,33,4,-5,61)) { ... }
I know you can't write an expression like this with 'in' because the lexer and parser of the compiler won't recognize it.
Perhaps other solutions as extension methods of different types of x is the solution?
In the coming .NET 4.0 i heard something about parameterized methods, should that solve the n amount of parameters supplied to the if-expression ?
Perhaps you understand me, have you an idea of a good practice/solution to this question?
/Daniel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我通常编写一个 扩展方法 如下:
可以这样使用:
I usually write an Extension Method as follows:
Which can be used like this:
尝试以下操作
Try the following
假设 x 是一个 int,你可以编写一个扩展方法,如下所示:
Given that x is an int you could write an extension method like so: