VB.Net Power operator (^) overloading from C#

空扰寡人 提交于 2020-01-21 06:49:05

问题


I am writing a C# class that is exposed to VB.Net. I would like to overload the vb.net ^ operator so that I can write:

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

In C#, the ^ operator is the xor operator and the power operator doesn't exist. Is there a way I can do this anyway?


回答1:


EDIT

It turns out there's a SpecialNameAttribute that lets you declare "special" functions in C# that will allow you (among other things) to overload the VB power operator:

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) };
    }
}

The op_Exponent function in the class above gets translated by VB into the ^ power operator.

Interestingly, the documentation states the Attribute in not currently used by the .NET framework...

--ORIGINAL ANSWER --

No. The power (^) operator gets compiled as Math.Pow() so there's no way to "overload" it in C#.

From 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



回答2:


By experiment, it turns out that operator overloading is just syntactic sugar, and better be avoided, if you need to develop in multiple languages. For example, ^ operator of VB.NET gets translated into op_Exponent function, so this is what's available to you from C#.

Why doesn't C# have a power operator?

You can use a native .NET way so you don't rely on operators:

Math.Pow(x, y);

Also for y=2 it is faster to use multiplication (x*x).



来源:https://stackoverflow.com/questions/13259162/vb-net-power-operator-overloading-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!