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# - 如何在 Ocelot 网关中处理 cors 策略和预检请求?

c# - 使用 .net、angular 和 electron 的桌面应用程序

c# - 如何让一个进程在 c#/.net 中的另一个进程中触发事件?

c# - 配置管理器类。锁定时无法编辑 ConfigurationSection 属性

c# - 使用给定文件夹中的源创建图像数组 C# Windows 桌面

c# - 为什么 string.TrimEnd 不只删除字符串中的最后一个字符

c# - 失去焦点时 Datagridview 单元格丢失输入值

.net - 命令失败后 Npgsql 不提交事务

c# - Linq 查询的性能(按类型)

c# - 人们如何在 C# 中重用混合风格?