如何延长密封类 - 需要简单的程序的解释和使用的实时实时、简单、程序

2023-09-05 04:34:54 作者:只对你有感觉

乡亲

我有一个密封类,如下所示。我想扩展这个密封类,以便增加一个将返回平均x和y的方法。这不是用这个:(可能有人请帮助我理解扩展密封类和实时使用情况和效益

I have a sealed class as follows. I want to extend this sealed class so as to add a method which will return average of x and y. This is not just extension method using "this" :( Could someone please help me understand the concept of "Extending Sealed class" and its "Real time usage and benefits"

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

感谢你......

推荐答案

由于@ReedCopsey已经指出的,这样延长密封类的功能是一个的扩展方法。这是一个会做什么,你都在问:

As @ReedCopsey has already pointed out, the way to extend the functionality of a sealed class is with an Extension Method. Here is one that will do what you are asking:

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);

修改按照要求,这里是所有code。在Visual Studio中的一个新的控制台应用程序,替换所有code。在的Program.cs 文件与下面的code和运行。

EDIT As requested, here is the all the code. Create a new Console Application in Visual Studio, replace all the code in the Program.cs file with the code below and run.

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();
        }
    }
}