第二个操作数的类型必须是 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...
...
编辑:
只是可以肯定......我可以重载 operator* 以获取(例如)字符串列表
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)。
真正的原因是它被制作了一个不清楚的代码?
最佳答案
是的。这是因为 language specification 需要它:
语言设计者不必做出这个决定——如果愿意,他们可以取消该限制——但我认为规范的这一部分解释了他们对运算符重载的这一(和其他)限制的推理:
他们可能希望移位运算符的行为总是像移位运算符一样,而不是完全令人惊讶。
关于c#-4.0 - C# 移位运算符重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7586887/