在不继承的情况下扩展类的方法
using System; namespace TTest { class Program { static void Main(string[] args) { string s = "abcdefg"; Console.WriteLine(s.StrExt()); ClassA ca = new ClassA(); ca.Fun1(); ca.Fun2(); Console.Read(); } } //扩展string类 public static class StringExtensions { public static string StrExt(this string str) { return str + "@Ext"; } } public class ClassA { public void Fun1() { Console.WriteLine("Fun1"); } } //扩展ClassA类 public static class ClassAExtensions { public static void Fun2(this ClassA a) { Console.WriteLine("Fun2"); } } }
运行测试