c# - 如何扩展一个密封类——需要简单的程序解释和实时使用

标签 c# .net

<分区>

亲们

我有一个密封类如下。我想扩展这个密封类,以便添加一个方法来返回 x 和 y 的平均值。这不仅仅是使用“this”的扩展方法:(有人可以帮助我理解“扩展密封类”的概念及其“实时用法和好处”

class Sealed A       
{ 
    int a; int b;    
    int Add (int x, int y)    
    {
        return x+y;
    }
}

谢谢....

最佳答案

正如@ReedCopsey 已经指出的那样,扩展密封类功能的方法是使用Extension Method。 .这是一个可以满足您要求的方法:

public sealed class MyClass       
{ 
    int a; int b;    
    int Add (int x, int y)    
    {
        return x + y;
    }
}

public static class MyClassExtensions
{
    public static decimal Average(this MyClass value,  int x, int y)
    {
        return (x + y)/2M;
    }
}

用法:

    var myClass = new MyClass();

    // returns 15
    var avg = myClass.Average(10, 20);

编辑 根据要求,这里是所有代码。在 Visual Studio 中创建一个新的控制台应用程序,将 Program.cs 文件中的所有代码替换为以下代码并运行。

using System;

namespace ConsoleApplication1
{
    public sealed class MyClass
    {
        public int X { get; private set; }
        public int Y { get; private set; }

        public MyClass(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        int Add()
        {
            return this.X + this.Y;
        }
    }

    public static class MyClassExtensions
    {
        public static decimal Average(this MyClass value)
        {
            return (value.X + value.Y) / 2M;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var myClass = new MyClass(10, 20);
            var avg = myClass.Average();

            Console.WriteLine(avg);
            Console.ReadLine();
        }
    }
}

关于c# - 如何扩展一个密封类——需要简单的程序解释和实时使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11234360/

相关文章:

c# - .Net中创建的内存不足异常对象在哪里?

c# - 从 Web.Config <appSettings> 部分 C#/MVC 连接到数据库

c# - 底层的 LINQ to SQL

c# - Microsoft.Build.Tasks.v12.0.dll 上的 UniversalApp 错误 "GenerateResource task failed unexpectedly"

c# - 为什么 Parallel.Foreach 会创建无限线程?

c# - 如何将双值格式化为没有货币符号的价格以及没有小数的特殊情况

c# - 从C#中的继承类获取变量

c# - 选择一个好的字典键

c# - 处理未使用的 IDisposable 返回值是否重要?

c# - Array.Reverse算法?