用于重载运算符的自定义字符串实现 << 和 >> 中字符串字符的二进制移位
本文关键字:字符串 字符 二进制 重载 运算符 实现 用于 自定义 | 更新日期: 2023-09-27 18:31:10
我想知道如何在 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);
}
}
}
如果我真的需要它,我会写一些类似的东西:
public static string operator << (MyString s, int shift)
{
if(shift <= 0)
{
return s;
}
shift = shift % s.Length;
return s.String.Substring(shift, s.Length - shift)
+ s.String.Substring(0, shift);
}
但是,目前尚不清楚为什么要以自己类的运算符的身份实现移位。只在字符串本身上定义一个扩展方法怎么样?然后,您将能够执行以下操作:
string str = "name".ShiftLeft(2);