我有一个结构命名空间,代表各种度量单位(米、英尺、英寸等)......总共有 12 个,由 T4 模板生成:)。
每个结构都带有隐式转换运算符以支持将值转换为任何其他测量值类型,因此以下语法是合法的:
var oneThousandMeters = new Meters(1000);
Kilometers aKilo = oneThousandMeters ; // implicit cast OK. Value = 1 Km
更有趣的是,有一个名为Distance的包罗万象的类,它可以保存任何测量单位,也可以隐式转换为和测量值......
var magnum = new Distance(12, DistanceUnits.Inches);
Feet wifesDelight = magnum; // implicit cast OK. Value = 1 foot.
遵循 .NET 框架标准,所有字符串格式化和解析都由实现 ICustomFormatter 的外部 FormatProvider 处理。遗憾的是,这意味着值在传递给 Format 方法时会被装箱,并且 format 方法需要针对每个已知的测量类型测试对象,然后才能对其进行操作。在内部,Format 方法只是将测量值转换为距离值,所以问题来了......
问题:
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Distance distance;
// The following line is desired, but fails if arg != typeof(Distance)
distance = (Distance)arg;
// But the following tedious code works:
if(arg is Distance)
distance = (Distance)arg;
else if(arg is Meters)
distance = (Distance)(Meters)arg; // OK. compile uses implicit cast.
else if(arg is Feet)
distance = (Distance)(Feet)arg; // OK. compile uses implicit cast.
else if(arg is Inches)
distance = (Distance)(Inches)arg; // OK. compile uses implicit cast.
else
... // tear you hair out for all 12 measurement types
}
是否有任何解决方案,或者这只是值类型的那些无法解决的缺点之一?
PS:我检查了这篇文章,虽然问题很相似,但这不是我要找的。