VB.Net Power运算符(^)从C#重载 [英] VB.Net Power operator (^) overloading from C#

查看:88
本文介绍了VB.Net Power运算符(^)从C#重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在C#中,^运算符是xor运算符,而幂运算符不存在.反正我有办法吗?

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

推荐答案

编辑

事实证明,有一个SpecialNameAttribute可以让您在C#中声明特殊"函数,从而(除其他事项外)使VB电源运算符超载:

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

上述类中的op_Exponent函数通过VB转换为^幂运算符.

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

有趣的是, documentation 指出.NET框架当前未使用的属性...

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

-原始答案-

不.幂(^)运算符被编译为Math.Pow(),因此无法在C#中重载"它.

No. The power (^) operator gets compiled as Math.Pow() so there's no way to "overload" it in 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 Power运算符(^)从C#重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆