8

我正在编写一个暴露给 VB.Net 的 C# 类。我想重载 vb.net^运算符,以便我可以编写:

Dim c as MyClass
Set c = New ...
Dim d as MyClass
Set d = c^2

在 C# 中,^运算符是xor运算符,不存在幂运算符。有没有办法我可以做到这一点?

4

2 回答 2

12

编辑

事实证明,有一个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) };
    }
}

VB 将上述类中的op_Exponent函数转换为^幂运算符。

有趣的是,文档说明了 .NET 框架当前未使用的属性...

--原始答案--

不。 power ( ^) 运算符被编译,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_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
于 2012-11-06T20:58:46.003 回答
2

通过实验,事实证明,运算符重载只是语法糖,如果您需要使用多种语言进行开发,最好避免。例如,^VB.NET 的运算符被翻译成op_Exponent函数,所以这就是 C# 中可用的。

为什么 C# 没有幂运算符?

您可以使用本机 .NET 方式,因此您不依赖运算符:

Math.Pow(x, y);

同样对于 y=2,使用乘法 (x*x) 会更快。

于 2012-11-06T20:54:25.823 回答