你将如何重构它,记住你还有几十个这样的度量要表示?这有点像将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;
}
}发布于 2008-12-24 06:30:20
我不会为每个权重创建单独的类。相反,让一个类代表一个单位,另一个类代表一个带有单位的数字:
/// <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对象只需按名称查找正确的单例。
发布于 2008-12-24 05:34:02
我想我会把它变成一个struct,这是大多数原语都是的。
https://stackoverflow.com/questions/390819
复制相似问题