动机:
在阅读 Mark Seemann 关于Code Smell: Automatic Property的博客时,他在接近尾声时说:
底线是自动属性很少适用。事实上,只有当属性的类型是值类型并且所有可能的值都被允许时,它们才合适。
他int Temperature
举了一个难闻的气味的例子,并建议最好的解决办法是像摄氏度这样的单位特定值类型。所以我决定尝试编写一个自定义的摄氏值类型,它封装了所有的边界检查和类型转换逻辑,作为更加SOLID的练习。
基本要求:
- 不可能有无效值
- 封装转换操作
- 有效应对(相当于 int 的替代)
- 尽可能直观地使用(尝试使用 int 的语义)
执行:
[System.Diagnostics.DebuggerDisplay("{m_value}")]
public struct Celsius // : IComparable, IFormattable, etc...
{
private int m_value;
public static readonly Celsius MinValue = new Celsius() { m_value = -273 }; // absolute zero
public static readonly Celsius MaxValue = new Celsius() { m_value = int.MaxValue };
private Celsius(int temp)
{
if (temp < Celsius.MinValue)
throw new ArgumentOutOfRangeException("temp", "Value cannot be less then Celsius.MinValue (absolute zero)");
if (temp > Celsius.MaxValue)
throw new ArgumentOutOfRangeException("temp", "Value cannot be more then Celsius.MaxValue");
m_value = temp;
}
public static implicit operator Celsius(int temp)
{
return new Celsius(temp);
}
public static implicit operator int(Celsius c)
{
return c.m_value;
}
// operators for other numeric types...
public override string ToString()
{
return m_value.ToString();
}
// override Equals, HashCode, etc...
}
测试:
[TestClass]
public class TestCelsius
{
[TestMethod]
public void QuickTest()
{
Celsius c = 41;
Celsius c2 = c;
int temp = c2;
Assert.AreEqual(41, temp);
Assert.AreEqual("41", c.ToString());
}
[TestMethod]
public void OutOfRangeTest()
{
try
{
Celsius c = -300;
Assert.Fail("Should not be able to assign -300");
}
catch (ArgumentOutOfRangeException)
{
// pass
}
catch (Exception)
{
Assert.Fail("Threw wrong exception");
}
}
}
问题:
- 有没有办法使 MinValue/MaxValue 变为 const 而不是只读?查看 BCL,我喜欢int的元数据定义如何清楚地将 MaxValue 和 MinValue 声明为编译时常量。我怎么能模仿呢?如果不调用构造函数或公开Celsius 存储int 的实现细节,我看不到创建Celsius 对象的方法。
- 我是否缺少任何可用性功能?
- 是否有更好的模式来创建自定义单字段值类型?