微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c#-4.0 – C#shift operator overload

有没有理由第二个操作数的类型必须是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 * for 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).

真的原因是它的代码不清楚了吗?

解决方法

是.这是因为 language specification需要它:

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.

语言设计者不必做出这样的决定 – 如果想要的话,他们可能会删除这个限制 – 但我认为规范的这一部分解释了他们对运算符重载的这个(和其他)限制的推理:

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.

他们可能希望bitshift运算符总是像bitshift运算符一样,而不是完全令人惊讶的东西.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐