C#中的全局类型别名

时间:2013-12-30 06:04:16

标签: c# types global using aliases

让我马上开始使用代码:

class Item {
    public int highestBuyOffer;
    public int lowestSellOffer;
    [...]
}

我希望阻止使用此类的人意外地将买入要约价值分配给卖出要约价值,反之亦然(如someBuyOffer = someSellOffer)。这就是我想创建自己的类型的原因:

class Item {
    public BuyOffer highestBuyOffer;
    public SellOffer lowestSellOffer;
    [...]
}

为它创建一个结构似乎有点过分,因为这些两个值的行为应该与int完全相同。

using指令不是我想要的,因为:

  1. 仅对一个文件
  2. 有效
  3. 它不算作类型,它只是一个同义词

1 个答案:

答案 0 :(得分:0)

我让这堂课涵盖了相同的需求:

public class NamedInt : IComparable<int>, IEquatable<int>
{
    internal int Value { get; }

    protected NamedInt() { }
    protected NamedInt(int val) { Value = val; }
    protected NamedInt(string val) { Value = Convert.ToInt32(val); }

    public static implicit operator int (NamedInt val) { return val.Value; }

    public static bool operator ==(NamedInt a, int b) { return a?.Value == b; }
    public static bool operator ==(NamedInt a, NamedInt b) { return a?.Value == b?.Value; }
    public static bool operator !=(NamedInt a, int b) { return !(a==b); }
    public static bool operator !=(NamedInt a, NamedInt b) { return !(a==b); }

    public bool Equals(int other) { return Equals(new NamedInt(other)); }
    public override bool Equals(object other) {
        if ((other.GetType() != GetType() && other.GetType() != typeof(string))) return false;
        return Equals(new NamedInt(other.ToString()));
    }
    private bool Equals(NamedInt other) {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return Equals(Value, other.Value);
    }

    public int CompareTo(int other) { return Value - other; }
    public int CompareTo(NamedInt other) { return Value - other.Value; }

    public override int GetHashCode() { return Value.GetHashCode(); }

    public override string ToString() { return Value.ToString(); }
}

在你的情况下消费它:

public class BuyOffer: NamedInt {
    public BuyOffer(int value) : base(value) { }
    public static implicit operator BuyOffer(int value) { return new BuyOffer(value); }
}

public class SellOffer: NamedInt {
    public SellOffer(int value) : base(value) { }
    public static implicit operator SellOffer(int value) { return new SellOffer(value); }
}

如果你需要能够序列化它(Newtonsoft.Json),请告诉我,我会添加代码。