【问题标题】:Global type aliases in C#C# 中的全局类型别名
【发布时间】:2014-01-17 00:35:25
【问题描述】:

让我从代码开始:

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

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

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

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

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

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

【问题讨论】:

  • 为什么在类中使用公共字段而不是属性?无论如何,在不了解更多需求的情况下,如果区分差异的逻辑很简单,请将它们设置为属性并在那里进行检查。如果逻辑更复杂,则只能通过实现逻辑的方法将字段设为私有和可设置。
  • 您实际上并不希望这两个值的行为与int 完全相同,因为如果他们这样做了,那么有效的操作就是将一个分配给另一个! (因为可以将int 分配给int。)您需要更准确地确定要允许的操作,并设置striut 以完全允许这些操作。
  • 我认为您在特定样本中寻找的功能是“测量单位”的版本(即Units of measure in C# 答案)。我认为您必须使用您感兴趣的所有操作来创建类型以支持您想要的内容(查看Custom compile-time checks 以了解如何在泛型类中拥有一个实现)。
  • 如果我尝试将一个与另一个相匹配,我想要的只是编译器错误。

标签: c# types global using aliases


【解决方案1】:

我开设这个课程是为了满足相同的需求:

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),请告诉我,我会添加代码。

【讨论】:

  • 只是......哇。好主意?馊主意? ...判断在旁观者的眼中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多