C# 移位运算符重载
第二个操作数的类型必须是 int 是否有原因?
...
// I would like to do this
public static StringList operator<<(StringList list, string s) {
list.Add(s);
return list;
}
// but only int is supported...
...
编辑: 可以肯定的是...我可以为 get 重载运算符*(例如)字符串列表,
class MyString {
string val;
public MyString(string s) {
val = s;
}
public static List<string> operator*(MyString s, int count) {
List<string> list = new List<string>();
while (count-- > 0) {
list.Add(s.val);
}
return list;
}
}
...
foreach (var s in new MyString("value") * 3) {
s.print(); // object extension (Console.WriteLine)
}
// output:
// value
// value
// value
...
但不能重载左移,这在 C++ std 中众所周知(为输出重载),因为不清楚? 当然,这只是 C# 设计者的决定。 尽管如此,它仍然可能在意外/不清楚的情况下重载(使用 int )。
真的是因为代码写的不清楚吗?
is there a reason for the type of the second operand must be int?
...
// I would like to do this
public static StringList operator<<(StringList list, string s) {
list.Add(s);
return list;
}
// but only int is supported...
...
EDIT:
Just for sure... I can overload operator* for get (for example) List of string
class MyString {
string val;
public MyString(string s) {
val = s;
}
public static List<string> operator*(MyString s, int count) {
List<string> list = new List<string>();
while (count-- > 0) {
list.Add(s.val);
}
return list;
}
}
...
foreach (var s in new MyString("value") * 3) {
s.print(); // object extension (Console.WriteLine)
}
// output:
// value
// value
// value
...
but cannot overload left shift, well known from C++ std (overloaded for output), because it was unclear?
Of course, it's just a decision of C# designers.
Still it can be overloaded on something unexpected/unclear (with int).
Really the reason is that it was made an unclear code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。这是因为语言规范需要它:
语言设计者不必做出这个决定 - 如果他们愿意的话,他们本来可以取消该限制 - 但我认为规范的这一部分解释了他们这样做的理由(并且other) 运算符重载的限制:
他们可能希望位移运算符始终表现得像位移运算符,而不是完全令人惊讶的东西。
Yes. It's because the language specification requires it:
The language designers didn't have to make that decision - it would have been possible for them to remove that restriction if the wanted to - but I think this part of the specification explains their reasoning for this (and other) restrictions on operator overloading:
They probably wanted the bitshift operators to always behave like bitshift operators, and not as something completely surprising.
因为你希望你的代码看起来像 C++?为什么不使用返回源列表的扩展方法
.Append( item )
。用作:
Because you want your code to look like c++? Why not an extension method
.Append( item )
that returns the source list.Used as: