开发者

How many overrides do you REALLY need in a struct in C#?

I am making a wrapper for a "word" in an emulator project. Its meant to put all my cast conversions all in one spot. I was just about to start implement all the overrides for math functions (+,-,/,8, shift, etc.) When it occured to me that shouldn't all the implicit's take care of that? Do I need to over ride >= and <= when I got > < and ==?

I thought I would ask this as while there are plenty of questions relating to how to create them, there aren't many on how much is enough. Here is the code below:

public struct word_t
{
    ulong val;
    word_t(ulong val) { this.val = val; }
    public static implicit operator word_t(int a) { return new word_t((ulong)a); }
    public static implicit operator word_t(long a) { return new word_t((ulong)a); }
    public static implicit operator word_t(uint a) { return new word_t((ulong)a); }
    public static implicit operator word_t(ulong a) { return new word_t((ulong)a); }
    public static implicit operator int(word_t a) { return (int)a.val; }
    public static implicit operator long(word_t a) { return (long)a.val; }
    public static implicit operator uint(word_t a) { return (uint)a.val; }
    public static implicit operator ulong(word_t a) { return (ulong)a.val; }
    public static bool operator ==(word_t a, word_t b) { return a.val == b.val; }
    public static bool operator !=(word_t a, word_t b) { return a.val != b.val; }
    public static bool operator >(word_t a, word_t b) { return a.val > b.val; }
    public static bool operator <(word_t a, word_t b) { return a.val < b.val; }
    public override bool Equals(object obj) {
            return obj.Equals(val);
    }
    public o开发者_JS百科verride int GetHashCode() {
        return val.GetHashCode();
    }
    public override string toString() {
        return val.ToString();
    }
}

My gut tells me to "Trust the compiler" but my head always worries on how efficient it is.

PS I just realized I should override shifts because of the bit shifting of negative number problems, but for right now just imagine shifts just magically work like adds between uint and int.


I recommend this MSDN article: http://msdn.microsoft.com/en-us/library/8edha89s(v=VS.100).aspx

It shows the operators you can overload and any catches. You can overload <= and >= but they must be overloaded in pairs, as is true with == and != as well.

The complex match operators +=, etc are available if +, etc. is overloaded, etc.

>= and <=, however, are separate. That is, overloading > and == does not give you a >= operator implicitly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜