c# - 重构;为您的应用程序域创建伪基元

标签 c#

您将如何重构它,同时牢记您还有数十个此类测量值要表示?这有点像将 int 更改为 short 或 long 或 byte。通用 unit<T> ?通过运算符重载进行隐式类型转换? ToType()图案?抽象基类? IConvertible

public class lb
{
    private readonly float lbs;
    private readonly kg kgs;

    public lb(float lbs)
    {
        this.lbs = lbs;
        this.kgs = new kg(lbs * 0.45359237F);
    }

    public kg ToKg()
    {
        return this.kgs; 
    }

    public float ToFloat()
    {
        return this.lbs;
    }
}

public class kg 
{
    private readonly float kgs;
    private readonly lb lbs;

    public kg(float kgs)
    {
        this.kgs = kgs;
        this.lbs = new lb(kgs * 2.20462262F);
    }

    public float ToFloat()
    {
        return this.kgs;
    }

    public lb ToLb()
    {
        return this.lbs;
    }
}

最佳答案

我不会为每个权重创建单独的类。相反,有一个类代表一个单位,另一个类代表一个带单位的数字:

/// <summary>
/// Class representing a unit of weight, including how to
/// convert that unit to kg.
/// </summary>
class WeightUnit
{
    private readonly float conv;
    private readonly string name;

    /// <summary>
    /// Creates a weight unit
    /// </summary>
    WeightUnit(float conv, string name)
    {
        this.conv = conv;
        this.name = name;
    }

    /// <summary>
    /// Returns the name of the unit
    /// </summary>
    public string Name { get { return name; } }

    /// <summary>
    /// Returns the multiplier used to convert this
    /// unit into kg
    /// </summary>
    public float convToKg { get { return conv; } }
};

/// <summary>
/// Class representing a weight, i.e., a number and a unit.
/// </summary>
class Weight
{
    private readonly float value;
    private readonly WeightUnit unit;

    public Weight(float value, WeightUnit unit)
    {
        this.value = value;
        this.unit = unit;
    }

    public float ToFloat()
    {
        return value;
    }

    public WeightUnit Unit
    {
        get { return unit; }
    }

    /// <summary>
    /// Creates a Weight object that is the same value
    /// as this object, but in the given units.
    /// </summary>
    public Weight Convert(WeightUnit newUnit)
    {
        float newVal = value * unit.convToKg / newUnit.convToKg;

        return new Weight(newVal, newUnit);
    }
};

这里的好处是,您可以从数据(可能是 XML 文件或资源)中将所有 WeightUnits 创建为单例对象,这样您就可以添加新单位而无需更改任何代码。创建一个 Weight 对象只是按名称查找正确的单例的问题。

关于c# - 重构;为您的应用程序域创建伪基元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/390819/

相关文章:

c# - 创建一个跨进程的 EventWaitHandle

c# - Linq to Entity Groupby 并连接列

javascript - 通过JavaScript或者dll或者jar文件获取客户端信息?

c# - 找不到 System.Windows 程序集

c# - 网络传输暂停

c# - 在循环中删除控件会导致奇怪的行为

c# - 在没有 SetSPN 的情况下查询/更改 Windows 域上的 SPN

c# - 为什么我无法访问 System.EventArgs 的 KeyCode 成员?

c# - SalesForce Web 服务 - 请求元素未被识别

c# - 如何使可移植 exe 程序 (C#) 使用本地网络上的数据库 (SQL Server Express)