扩展方法可以向已经编译好的类中注入其他方法。
方法是:将需要扩展的类声明为static类中的Static方法。它的第一个参数是针对何种类型,要加入this关键字。
有了这个特性,你可以写自己的通用类库支持多种扩张。比如验证类。。。
示例:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace TestCS
{
//必须是静态的类
static class MyExtension
{
//必须是静态的方法。且参数列表中含有 this
public static void DisplayToString(this object o)
{
Console.WriteLine(o.ToString());
}
public static void Foo(this int i)
{
Console.WriteLine("Calling Foo {0}", i);
}
public static void Foo(this int i, string msg)
{
Console.WriteLine("Calling Foo {0}, {1}", i, msg);
}
}
static class CarExtense
{
public static void SlowDown(this Car c,int delta)
{
c.CurrentSpeed-=delta;
Console.WriteLine("Car is slowing dow..... at a speed of {0}", c.CurrentSpeed);
}
}
class Program
{
static void Main(string[] args)
{
//实例引用
//值类型
int myInt = 343;
myInt.DisplayToString();
myInt.Foo("xx");
//实例引用
//引用类型
System.Data.DataSet ds = new System.Data.DataSet();
ds.DisplayToString();
//静态引用
MyExtension.DisplayToString(myInt);
MyExtension.Foo(myInt);
//Car的应用
Car c = new Car("pet",200);
c.Accelerate(100);
c.SlowDown(100);
}
}
}
本文介绍了C#中的扩展方法概念及其实现方式。通过具体的代码示例展示了如何为已有的类添加新的静态方法,实现对象的功能扩展。文章还提供了几个实用的扩展方法案例,如显示对象字符串表示形式和车辆减速功能。
1143

被折叠的 条评论
为什么被折叠?



