c# - 将静态方法附加到类而不是类实例的最佳方法是什么?

标签 c# .net math extension-methods language-features

如果我有一个计算两个整数的最大公约数的方法:

public static int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}

将其附加到 System.Math 类的最佳方法是什么?

以下是我想出的三种方法:

public static int GCD(this int a, int b)
{
    return b == 0 ? a : b.GCD(a % b);
}

// Lame...

var gcd = a.GCD(b);

和:

public static class RationalMath
{
    public static int GCD(int a, int b)
    {
        return b == 0 ? a : GCD(b, a % b);
    }
}

// Lame...

var gcd = RationalMath.GCD(a, b);

和:

public static int GCD(this Type math, int a, int b)
{
    return b == 0 ? a : typeof(Math).GCD(b, a % b);
}

// Neat?

var gcd = typeof(Math).GCD(a, b);

所需的语法是 Math.GCD,因为这是所有数学函数的标准。

有什么建议吗?我应该怎么做才能获得所需的语法?

最佳答案

你不能。扩展方法只是调用静态函数和传递特定类型实例的语法糖。鉴于此,它们仅在实例上运行,因为它们必须通过传递您要附加到的类型的 this 参数来定义。

关于c# - 将静态方法附加到类而不是类实例的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2545223/

相关文章:

c# - Windows 窗体图标未显示在任务栏 C#

c# - Linq to SQL 立即执行查询

c# - 为测验评分的正确方法

c# - 带有 dotnetopenauth 的 Google Hybrid OpenID+OAuth

c# - 首先在 Entity Framework 代码中定义外键

c# - 如何在控件中使用 PreLoad 事件?

python 没有正确绘制 "tangent"函数

python - 数学表达式评估

java - 从频率数组中获取中值?

c# - KnockoutJS 的购物车逻辑(?)问题