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

前端之家收集整理的这篇文章主要介绍了VB.Net Power运算符(^)从C#重载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个暴露给VB.Net的C#类.我想重载vb.net ^运算符,以便我可以写:
  1. Dim c as MyClass
  2. Set c = New ...
  3. Dim d as MyClass
  4. Set d = c^2

在C#中,^运算符是xor运算符,幂运算符不存在.有没有办法可以做到这一点?

编辑

事实证明,有一个SpecialNameAttribute允许您在C#中声明“特殊”函数,这将允许您(除其他外)重载VB电源运算符:

  1. public class ExponentClass
  2. {
  3. public double Value { get; set; }
  4.  
  5. [System.Runtime.CompilerServices.SpecialName]
  6. public static ExponentClass op_Exponent(ExponentClass o1,ExponentClass o2)
  7. {
  8. return new ExponentClass { Value = Math.Pow(o1.Value,o2.Value) };
  9. }
  10. }

上面的类中的op_Exponent函数由VB转换为^幂运算符.

有趣的是,documentation声明了.NET框架当前未使用的属性

– 原始答案 –

不.幂(^)运算符被编译为Math.Pow(),所以没有办法在C#中“重载”它.

来自LinqPad:

  1. Sub Main
  2. Dim i as Integer
  3. Dim j as Integer
  4. j = Integer.Parse("6")
  5. i = (5^j)
  6. i.Dump()
  7. End Sub

IL:

  1. IL_0001: ldstr "6"
  2. IL_0006: call System.Int32.Parse
  3. IL_000B: stloc.1
  4. IL_000C: ldc.r8 00 00 00 00 00 00 14 40
  5. IL_0015: ldloc.1
  6. IL_0016: conv.r8
  7. IL_0017: call System.Math.Pow
  8. IL_001C: call System.Math.Round
  9. IL_0021: conv.ovf.i4
  10. IL_0022: stloc.0
  11. IL_0023: ldloc.0
  12. IL_0024: call LINQPad.Extensions.Dump

猜你在找的VB相关文章