代码之家  ›  专栏  ›  技术社区  ›  Jerry

您如何扩展(或可以扩展)静态数学方法?

  •  10
  • Jerry  · 技术社区  · 17 年前

    有了C#3.0,我知道可以使用“this”术语扩展方法。

    在尝试了一些新事物之后,我将返回SO以获取输入。我卡住了。

    这是我在这一点上得到的。。。

    public class EngMath
    {
        /// ---------------------------------------------------------------------------
        /// Extend the Math Library to include EngVar objects.
        /// ---------------------------------------------------------------------------
    
        public static EngVar Abs(this Math m, EngVar A)
        {
            EngVar C = A.Clone();
    
            C.CoreValue = Math.Abs(C.CoreValue);
    
            return C;
        }
    
        public static EngVar Cos(this Math m, EngVar A)
        {
            EngVar C = A.Clone();
            double Conversion = 1;
            // just modify the value. Don't modify the exponents at all
    
            // is A degrees? If so, convert to radians.
            if (A.isDegrees) Conversion = 180 / Math.PI;
    
            C.CoreValue = Math.Cos(A.CoreValue * Conversion);
    
            // if A is degrees, convert BACK to degrees.
            C.CoreValue *= Conversion;
    
            return C;
        }
    
        ...
    
    1 回复  |  直到 10 年前
        1
  •  14
  •   Brian Rasmussen    17 年前

    扩展方法是一种使静态方法看起来像它们“扩展”类型上的实例方法的方法。换句话说,为了使用扩展方法特性,您需要某个对象的实例。

    在我听来,你正以相反的方式尝试数学,因为你可以处理你的类型。在这种情况下,恐怕您必须自己实现该功能。如果这不是你想要做的,请澄清。