微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB.Net Power运算符(^)从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转换为^幂运算符.

有趣的是,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

原文地址:https://www.jb51.cc/vb/255050.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐