c# - VB.Net Power 运算符 (^) 从 C# 重载

标签 c# vb.net operator-overloading operator-keyword

我正在编写一个暴露给 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 翻译成 ^ 幂运算符。

有趣的是,documentation声明 .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

关于c# - VB.Net Power 运算符 (^) 从 C# 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259162/

相关文章:

c++ - 为什么运算符重载表现如此奇怪

c# - 在同一项目中混合使用 C# 和 VB

c++ - 在 vector 中的派生类上调用重载的 << 运算符

c# - 依赖属性优化?

c# - 如何更新 .NET 中现有配置键的值?

c# - 打开和打印 PDF 文件

c# - 从 Azure Ping 客户端 LAN

java - 如何使用 Visual Basic 向需要字符串的服务器发出 POST 请求?

c# - ASP Web 应用程序可以写入最终用户计算机上的日志文件吗

swift - 我应该更喜欢运算符重载而不是函数/方法吗?