开发者

C# shift operator overload

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?


Yes. It's because the language specification requires it:

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.


Because you want your code to look like c++? Why not an extension method .Append( item ) that returns the source list.

public static class ListExtensions
{
    public static List<T> Append<T>( this List<T> source, T item )
    {
        if (source == null)
        {
            throw new NullArgumentException( "source" );
        }
        source.Add(item);
        return source;
    }
}

Used as:

var list = new List<string>();
list.Append( "foo" )
    .Append( "bar" )
    .Append( "baz" );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜