C#移位运算符重载 [英] C# shift operator overload

查看:95
本文介绍了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...
...

可以肯定的是...我可以重载operator *以获取(例如)字符串列表

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
...

但是不能重载左移,这在C ++ std中很常见(为输出重载),因为尚不清楚? 当然,这只是C#设计人员的决定. 仍然可以在意外/不清楚的地方(带有int)重载它.

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?

推荐答案

是.这是因为语言规范需要它:

在声明重载的移位运算符时,第一个操作数的类型必须始终是包含该运算符声明的类或结构,而第二个操作数的类型必须始终为int.

When declaring an overloaded shift operator, the type of the first operand must always be the class or struct containing the operator declaration, and the type of the second operand must always be int.

语言设计者没有没有做出决定-如果愿意,他们有可能消除该限制-但我认为规范的这一部分解释了他们的理由运算符重载的这个(和其他)限制:

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:

尽管用户定义的运算符可以执行自己喜欢的任何计算,但强烈建议不要生成除直观期望之外的结果的实现.

While it is possible for a user-defined operator to perform any computation it pleases, implementations that produce results other than those that are intuitively expected are strongly discouraged.

他们可能希望位移位运算符始终像位移位运算符一样工作,而不是完全令人惊讶.

They probably wanted the bitshift operators to always behave like bitshift operators, and not as something completely surprising.

这篇关于C#移位运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆