0

我想知道如何在 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);
    }
}

}

4

1 回答 1

3

如果我真的需要它,我会写一些类似的东西:

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);
}

但是,尚不清楚您为什么要将 shift 实现为您自己的类的运算符。仅仅在 String 本身上定义一个扩展方法怎么样?然后,您将能够执行以下操作:

string str = "name".ShiftLeft(2);
于 2012-04-14T08:44:53.217 回答