我想知道如何在 c# 中实现 MyString 类并重载运算符<<
和>>
. 例如 :
MyString name = "string";
Console.Write(name<<3) // It will print **ingstr** by shifting last 3 to left
我目前的实现如下:
public sealed class MyString
{
private readonly string _value="";
public MyString(string str)
{
_value = str;
}
public override string ToString()
{
return _value;
}
public static implicit operator MyString(string str)
{
var myString = new MyString(str);
return myString;
}
public static explicit operator string(MyString myString)
{
return myString._value;
}
public override bool Equals(Object obj)
{
if (obj == null)
{
return false;
}
var s = obj as MyString;
if ((object)s == null)
return false;
return _value.Equals(obj);
}
public bool Equals(MyString str)
{
return _value.Equals(str);
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public static bool operator ==(MyString a, MyString b)
{
return a._value.Equals(b.ToString());
}
public static bool operator !=(MyString a, MyString b)
{
return !(a == b);
}
public static MyString operator <<(MyString s, int shift)
{
if (shift <= 0)
{
return s;
}
shift = shift % s._value.Length;
return s._value.Substring(shift, s._value.Length - shift)
+ s._value.Substring(0, shift);
}
public static MyString operator >>(MyString s, int shift)
{
if (shift <= 0)
return s;
shift = shift%s._value.Length;
return s._value.Substring(shift, s._value.Length - shift) + s._value.Substring(0,shift);
}
}
}