[英]VB.Net Power operator (^) overloading from C#
我正在編寫一個暴露給VB.Net的C#類。 我想重載vb.net ^
運算符,以便我可以寫:
Dim c as MyClass
Set c = New ...
Dim d as MyClass
Set d = c^2
在C#中, ^
運算符是xor
運算符,冪運算符不存在。 有沒有辦法可以做到這一點?
編輯
事實證明,有一個SpecialNameAttribute
允許您在C#中聲明“特殊”函數,這將允許您(除其他外)重載VB電源運算符:
public class ExponentClass
{
public double Value { get; set; }
[System.Runtime.CompilerServices.SpecialName]
public static ExponentClass op_Exponent(ExponentClass o1, ExponentClass o2)
{
return new ExponentClass { Value = Math.Pow(o1.Value, o2.Value) };
}
}
上面的類中的op_Exponent
函數由VB轉換為^
冪運算符。
有趣的是, 文檔說明了.NET框架當前未使用的屬性...
- 原始答案 -
不。冪( ^
)運算符被編譯為Math.Pow()
所以沒有辦法在C#中“重載”它。
來自LinqPad:
Sub Main
Dim i as Integer
Dim j as Integer
j = Integer.Parse("6")
i = (5^j)
i.Dump()
End Sub
IL:
IL_0001: ldstr "6"
IL_0006: call System.Int32.Parse
IL_000B: stloc.1
IL_000C: ldc.r8 00 00 00 00 00 00 14 40
IL_0015: ldloc.1
IL_0016: conv.r8
IL_0017: call System.Math.Pow
IL_001C: call System.Math.Round
IL_0021: conv.ovf.i4
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: call LINQPad.Extensions.Dump
通過實驗,結果表明運算符重載只是語法糖,如果你需要用多種語言開發,最好避免使用。 例如,VB.NET的^
運算符被轉換為op_Exponent
函數,因此這是C#可以使用的。
您可以使用本機.NET方式,因此您不依賴於運算符:
Math.Pow(x, y);
同樣,對於y = 2,使用乘法(x * x)更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.