[英]VB.Net Power operator (^) overloading from C#
I am writing a C# class that is exposed to VB.Net. 我正在编写一个暴露给VB.Net的C#类。 I would like to overload the vb.net
^
operator so that I can write: 我想重载vb.net
^
运算符,以便我可以写:
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. 在C#中,
^
运算符是xor
运算符,幂运算符不存在。 Is there a way I can do this anyway? 有没有办法可以做到这一点?
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: 事实证明,有一个
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) };
}
}
The op_Exponent
function in the class above gets translated by VB into the ^
power operator. 上面的类中的
op_Exponent
函数由VB转换为^
幂运算符。
Interestingly, the documentation states the Attribute in not currently used by the .NET framework... 有趣的是, 文档说明了.NET框架当前未使用的属性...
--ORIGINAL ANSWER -- - 原始答案 -
No. The power ( ^
) operator gets compiled as Math.Pow()
so there's no way to "overload" it in C#. 不。幂(
^
)运算符被编译为Math.Pow()
所以没有办法在C#中“重载”它。
From LinqPad: 来自LinqPad:
Sub Main
Dim i as Integer
Dim j as Integer
j = Integer.Parse("6")
i = (5^j)
i.Dump()
End Sub
IL: 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
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#. 例如,VB.NET的
^
运算符被转换为op_Exponent
函数,因此这是C#可以使用的。
Why doesn't C# have a power operator? 为什么C#没有电源运营商?
You can use a native .NET way so you don't rely on operators: 您可以使用本机.NET方式,因此您不依赖于运算符:
Math.Pow(x, y);
Also for y=2 it is faster to use multiplication (x*x). 同样,对于y = 2,使用乘法(x * x)更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.