简体   繁体   English

创建一个评估为两倍的自定义类型

[英]Creating a custom type that evaluates to double

I'm currently working on a class RoundedDouble . 我目前正在研究RoundedDouble类。 The aim of this class is to provide an alternative to the .Net double struct. 此类的目的是为.Net double结构提供替代方法。 It should work similarly to a double but that is rounded to a number of decimal places. 它的工作方式与double相似,但四舍五入到小数点后一位。 At first we just wanted to have formatted numbers at the user interface level, but we're stuck with the requirement that we need to ensure that the value shown in the user interface is the value used in the calculation (limited precision of a double is accepted). 起初,我们只是想在用户界面级别设置数字格式,但是我们坚持要求确保用户界面中显示的值是计算中使用的值(双精度精度为公认)。 That means a value that round to 2 decimals and was entered as 1.23456789 should evaluate to 1.23. 这意味着一个四舍五入到小数点后两位并输入为1.23456789的值应计算为1.23。

(Using a custom TypeConverter is something we have considered as an alternative, but we opted for the RoundedDouble as that would allow us with arithmetic that preserves the lowest precision similar to calculating with number and taking their significance/accuracy into account.) (使用自定义TypeConverter是我们的替代选择,但我们选择了RoundedDouble ,因为这将使我们能够保持算术精度最低,类似于计算数字并考虑其重要性/准确性。)

Now I have implemented IEquatable<Double> for the RoundedDouble class and I've hit a snag for the following situation: 现在,我为RoundedDouble类实现了IEquatable<Double> ,并且遇到了以下情况:

object roundedDoubleBoxedAsObject = new RoundedDouble(2, 1.23456789); //1st param is the number of decimal places
double expectedValue = 1.23;
Debug.Assert(Equals(roundedDoubleBoxedAsObject, expectedValue)); // Passes, as RoundedDouble.Equals(double) is called
Debug.Assert(Equals(expectedValue, roundedDoubleBoxedAsObject),
             "Rounded value should be considered equal."); // <-- Fails, because Double.Equals(object) is called!

I've already implemented an implicit conversion from RoundedDouble to Double that already covers a lot of problems. 我已经实现了从RoundedDouble到Double的隐式转换,该转换已经涵盖了很多问题。 But when RoundedDouble is boxed as an object, the implicit conversion is circumvented. 但是,如果将RoundedDouble装箱为对象,则会绕过隐式转换。

Is this problem even solvable in C#? 这个问题在C#中甚至可以解决吗? Or have I hit a limit in the programming language? 还是我达到了编程语言的极限?

It seems that the problem of boxed comparison is already a challenge present in C# v4.0 as using System.Object.Equals(Object) will not work as you expected in cases like these: 盒装比较问题似乎已经是C#v4.0中存在的一个挑战,因为在以下情况下,使用System.Object.Equals(Object)将无法按预期工作:

double oneAsDouble = 1.0;
int oneAsInteger = 1;
Debug.Assert(oneAsDouble.Equals(oneAsInteger)); // Pass
Debug.Assert(oneAsInteger.Equals(oneAsDouble)); // Pass
Debug.Assert(Equals((object)oneAsDouble, (object)oneAsInteger)); // <-- Fails!
Debug.Assert(oneAsDouble.Equals((object)OneAsInteger)); // <-- Fails!
Debug.Assert(oneAsInteger.Equals((object)oneAsDouble)); // <-- Fails!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM