[英]Type safety in C# using custom ValueType
在我的代码中,我有System.Double 类型的变量,它们代表数量或数量差异。 为了使我的代码更安全,我想传入一个Quantity 或 QuantityDelta 类型的值,而不是 double (以避免传入错误的值)。
我可以创建一个带有 Value 属性或字段的结构或类,但是我必须为其分配内存并使用 .Value 语法来使用它:
public class Quantity
{
public Quantity(double value) { Value = value; }
public double Value;
}
和
var difference = new Quantity(differenceValue);
var used = difference.Value;
有没有办法为此目的创建自定义值类型,所以代码看起来像
Quantity difference = differenceValue;
var used = difference
使用隐式运算符。
public struct Quantity
{
private readonly double value;
public Quantity(double value) { this.value = value; }
public double Value => value;
public static implicit operator double(Quantity value) => value.value;
public static implicit operator Quantity(double value) => new Quantity(value);
}
此外,由于您只是包装值类型,因此最好使用struct
而不是class
。
运算符重载将有助于Quantity difference = differenceValue;
,特别是用于将双精度值转换为 Quantity 结构实例的隐式转换运算符。
但是,没有什么能帮助您说服编译器为var used = difference
中的 var 声明的used变量选择double类型。 因为var
指示编译器使用右侧表达式的类型作为 var 声明的变量used的类型。 这里是数量。 即,编译器会将var used = difference
理解为Quantity used = difference
。
这是我为具有加法、减法、乘法和除法的基本操作的Quantity
结构创建的快速示例。
public readonly struct Quantity
{
private readonly double num;
public Quantity(double number)
{
num = number;
}
public static Quantity operator +(Quantity a, Quantity b) => new Quantity(a.num + b.num);
public static Quantity operator -(Quantity a, Quantity b) => new Quantity(a.num - b.num);
public static Quantity operator *(Quantity a, Quantity b) => new Quantity(a.num * b.num);
public static Quantity operator /(Quantity a, Quantity b)
{
if (b.num == 0)
{
throw new DivideByZeroException();
}
return new Quantity(a.num / b.num);
}
public override string ToString() => $"{num}";
}
几个快速测试用例
var a = new Quantity(5);
var b = new Quantity(2);
Debug.WriteLine(a + b); // output: 7
Debug.WriteLine(a - b); // output: 3
Debug.WriteLine(a * b); // output: 10
Debug.WriteLine(a / b); // output: 2.5
如果您确实希望在名为QuantityDelta
的类型中返回差异,您可以将上面的-
运算符替换为:
公共静态 QuantityDelta 运算符 -(Quantity a, Quantity b) => new QuantityDelta(a.num - b.num);
并且,按照以下方式添加一个新的QuantityDelta
结构:
public readonly struct QuantityDelta
{
private readonly double num;
public QuantityDelta(double number)
{
num = number;
}
public override string ToString() => $"{num}";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.