Skip to main content
 首页 » 编程设计

Scala 相当于 C# 的扩展方法

2024年02月27日20xing901022

在 C# 中你可以这样写:

using System.Numerics; 
namespace ExtensionTest { 
public static class MyExtensions { 
    public static BigInteger Square(this BigInteger n) { 
        return n * n; 
    } 
    static void Main(string[] args) { 
        BigInteger two = new BigInteger(2); 
        System.Console.WriteLine("The square of 2 is " + two.Square()); 
    } 
}} 

这个简单的extension method怎么样?看起来像 Scala 中的吗?

请您参考如下方法:

Pimp My Library模式是类似的结构:

object MyExtensions { 
  implicit def richInt(i: Int) = new { 
    def square = i * i 
  } 
} 
 
 
object App extends Application { 
  import MyExtensions._ 
 
  val two = 2 
  println("The square of 2 is " + two.square) 
 
} 
<小时 />

根据 @Daniel Spiewak 的评论,这将避免方法调用的反射,从而提高性能:

object MyExtensions { 
  class RichInt(i: Int) { 
    def square = i * i 
  } 
  implicit def richInt(i: Int) = new RichInt(i) 
}