您将如何重构它,同时牢记您还有数十个此类测量值要表示?这有点像将 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/