[英]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.