首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重构;为应用程序域创建伪原语

重构;为应用程序域创建伪原语
EN

Stack Overflow用户
提问于 2008-12-24 05:27:56
回答 2查看 136关注 0票数 1

你将如何重构它,记住你还有几十个这样的度量要表示?这有点像将int更改为short、long或byte。泛型unit<T>?通过操作符重载进行隐式类型转换?ToType()模式?抽象基类-- IConvertible

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2008-12-24 06:30:20

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

代码语言:javascript
复制
/// <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对象只需按名称查找正确的单例。

票数 4
EN

Stack Overflow用户

发布于 2008-12-24 05:34:02

我想我会把它变成一个struct,这是大多数原语都是的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/390819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档