乡亲
我有一个密封的课程如下.我想扩展这个密封类,以便添加一个返回x和y平均值的方法.这不仅仅是使用"this"的扩展方法:(有人可以帮我理解"扩展密封类"的概念及其"实时使用和效益"
class Sealed A
{
int a; int b;
int Add (int x, int y)
{
return x+y;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢....
Kev*_*mey 18
正如@ReedCopsey已经指出的那样,扩展密封类功能的方法是使用扩展方法.这是一个会做你要求的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var myClass = new MyClass();
// returns 15
var avg = myClass.Average(10, 20);
Run Code Online (Sandbox Code Playgroud)
编辑根据要求,这是所有代码.在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
请有人帮我理解"扩展密封课程"的概念及其"实时使用和福利"
基本概念是密封类意味着您不能继承(扩展)它.这就是班级被密封的全部原因- 这会"密封"班级,因此无法扩展.
扩展方法允许您创建一个似乎扩展类的方法,但实际上是一个普通的静态方法.编译器调用此方法,并传递类实例.
| 归档时间: |
|
| 查看次数: |
15034 次 |
| 最近记录: |