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运算符一样,而不是完全令人惊讶的东西.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...