<分区>
亲们
我有一个密封类如下。我想扩展这个密封类,以便添加一个方法来返回 x 和 y 的平均值。这不仅仅是使用“this”的扩展方法:(有人可以帮助我理解“扩展密封类”的概念及其“实时用法和好处”
class Sealed A
{
int a; int b;
int Add (int x, int y)
{
return x+y;
}
}
谢谢....
<分区>
亲们
我有一个密封类如下。我想扩展这个密封类,以便添加一个方法来返回 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/