C#中增強(qiáng)類功能的幾種方式詳解
前言
本文主要講解如何利用C#語言自身的特性來對(duì)一個(gè)類的功能進(jìn)行豐富與增強(qiáng),便于拓展現(xiàn)有項(xiàng)目的一些功能。
拓展方法
擴(kuò)展方法被定義為靜態(tài)方法,通過實(shí)例方法語法進(jìn)行調(diào)用。方法的第一個(gè)參數(shù)指定該方法作用于哪個(gè)類型,并且該參數(shù)以 this 修飾符為前綴。僅當(dāng)使用 using 指令將命名空間顯式導(dǎo)入到源代碼中之后,擴(kuò)展方法才可使用。
namespace Extensions { public static class StringExtension { public static DateTime ToDateTime(this string source) { DateTime.TryParse(source, out DateTime result); return result; } } }
注意:
- 如果擴(kuò)展方法與該類型中定義的方法具有相同的簽名,則擴(kuò)展方法永遠(yuǎn)不會(huì)被調(diào)用。
- 在命名空間級(jí)別將擴(kuò)展方法置于相應(yīng)的作用范圍內(nèi)。例如,在一個(gè)名為 Extensions 的命名空間中具有多個(gè)包含擴(kuò)展方法的靜態(tài)類,則在使用這些拓展方法時(shí),必須引用其命名空間 using Extensions
繼承
繼承 面向?qū)ο蟮囊粋€(gè)特性,屬于Is a 關(guān)系,比如說Student繼承Person,則說明Student is a Person。子類可以通過重寫父類的方法或添加新的方法來實(shí)現(xiàn)對(duì)父類的拓展。
namespace Inherit { public class Persion { public string Name { get; set; } public int Age { get; set; } public void Eat() { Console.WriteLine("吃飯"); } public void Sleep() { Console.WriteLine("睡覺"); } } public class Student : Persion { public void Study() { Console.WriteLine("學(xué)習(xí)"); } public new void Sleep() { Console.WriteLine("做作業(yè),復(fù)習(xí)功課"); base.Sleep(); } } }
繼承的缺點(diǎn):
- 父類的內(nèi)部細(xì)節(jié)對(duì)子類是可見的
- 子類與父類的繼承關(guān)系在編譯階段就確定下來了,無法在運(yùn)行時(shí)動(dòng)態(tài)改變從父類繼承方法的行為
- 如果父類方法做了修改,所有的子類都必須做出相應(yīng)的調(diào)整,子類與父類是一種高度耦合,違反了面向?qū)ο蟮乃枷搿?/li>
組合
組合就是在設(shè)計(jì)類的時(shí)候把需要用到的類作為成員變量加入到當(dāng)前類中。
組合的優(yōu)缺點(diǎn):
優(yōu)點(diǎn):
- 隱藏了被引用對(duì)象的內(nèi)部細(xì)節(jié)
- 降低了兩個(gè)對(duì)象之間的耦合
- 可以在運(yùn)行時(shí)動(dòng)態(tài)修改被引用對(duì)象的實(shí)例
缺點(diǎn):
- 系統(tǒng)變更可能需要不停的定義新的類
- 系統(tǒng)結(jié)構(gòu)變復(fù)雜,不再局限于單個(gè)類
建議多使用組合,少用繼承
裝飾者模式
裝飾者模式指在不改變?cè)惗x及繼承關(guān)系的情況跟下,動(dòng)態(tài)的拓展一個(gè)類的功能,就是利用創(chuàng)建一個(gè)包裝類(wrapper)來裝飾(decorator)一個(gè)已有的類。
包含角色:
被裝飾者:
- Component 抽象被裝飾者,
- ConcreteComponent 具體被裝飾者,Component的實(shí)現(xiàn),在裝飾者模式中裝飾的就是這貨。
裝飾者:
- Decorator 裝飾者 一般是一個(gè)抽象類并且作為Component的子類,Decorator必然會(huì)有一個(gè)成員變量用來存儲(chǔ)Component的實(shí)例
- ConcreateDecorator 具體裝飾者 Decorator的實(shí)現(xiàn)
在裝飾者模式中必然會(huì)有一個(gè)最基本,最核心,最原始的接口或抽象類充當(dāng)component和decorator的抽象組件
實(shí)現(xiàn)要點(diǎn):
- 定義一個(gè)類或接口,并且讓裝飾者及被裝飾者的都繼承或?qū)崿F(xiàn)這個(gè)類或接口
- 裝飾者中必須持有被裝飾者的引用
- 裝飾者中對(duì)需要增強(qiáng)的方法進(jìn)行增強(qiáng),不需要增強(qiáng)的方法調(diào)用原來的業(yè)務(wù)邏輯
namespace Decorator { /// <summary> /// Component 抽象者裝飾者 /// </summary> public interface IStudent { void Learn(); } /// <summary> /// ConcreteComponent 具體被裝飾者 /// </summary> public class Student : IStudent { private string _name; public Student(string name) { this._name = name; } public void Learn() { System.Console.WriteLine(this._name + "學(xué)習(xí)了以上內(nèi)容"); } } /// <summary> /// Decorator 裝飾者 /// </summary> public abstract class Teacher : IStudent { private IStudent _student; public Teacher(IStudent student) { this._student = student; } public virtual void Learn() { this.Rest(); this._student.Learn(); } public virtual void Rest() { Console.WriteLine("課間休息"); } } /// <summary> /// ConcreteDecorator 具體裝飾者 /// </summary> public class MathTeacher : Teacher { private String _course; public MathTeacher(IStudent student, string course) : base(student) { this._course = course; } public override void Learn() { System.Console.WriteLine("學(xué)習(xí)新內(nèi)容:" + this._course); base.Learn(); } public override void Rest() { System.Console.WriteLine("課間不休息,開始考試"); } } /// <summary> /// ConcreteDecorator 具體裝飾者 /// </summary> public class EnlishTeacher : Teacher { private String _course; public EnlishTeacher(IStudent student, string course) : base(student) { this._course = course; } public override void Learn() { this.Review(); System.Console.WriteLine("學(xué)習(xí)新內(nèi)容:" + this._course); base.Learn(); } public void Review() { System.Console.WriteLine("復(fù)習(xí)英文單詞"); } } public class Program { static void Main(string[] args) { IStudent student = new Student("student"); student = new MathTeacher(student, "高數(shù)"); student = new EnlishTeacher(student, "英語"); student.Learn(); } } }
裝飾者模式優(yōu)缺點(diǎn):
優(yōu)點(diǎn):
- 裝飾者與被裝飾者可以獨(dú)立發(fā)展,不會(huì)互相耦合
- 可以作為繼承關(guān)系的替代方案,在運(yùn)行時(shí)動(dòng)態(tài)拓展類的功能
- 通過使用不同的裝飾者類或不同的裝飾者排序,可以得到各種不同的結(jié)果
缺點(diǎn):
- 產(chǎn)生很多裝飾者類
- 多層裝飾復(fù)雜
代理模式
代理模式就是給一個(gè)對(duì)象提供一個(gè)代理對(duì)象,并且由代理控制原對(duì)象的引用。
包含角色:
- 抽象角色:抽象角色是代理角色和被代理角色的所共同繼承或?qū)崿F(xiàn)的抽象類或接口
- 代理角色:代理角色是持有被代理角色引用的類,代理角色可以在執(zhí)行被代理角色的操作時(shí)附加自己的操作
- 被代理角色:被代理角色是代理角色所代理的對(duì)象,是真實(shí)要操作的對(duì)象
靜態(tài)代理
動(dòng)態(tài)代理涉及到反射技術(shù)相對(duì)靜態(tài)代理會(huì)復(fù)雜很多,掌握好動(dòng)態(tài)代理對(duì)AOP技術(shù)有很大幫助
namespace Proxy { /// <summary> /// 共同抽象角色 /// </summary> public interface IBuyHouse { void Buy(); } /// <summary> /// 真實(shí)買房人,被代理角色 /// </summary> public class Customer : IBuyHouse { public void Buy() { System.Console.WriteLine("買房子"); } } /// <summary> /// 中介-代理角色 /// </summary> public class CustomerProxy : IBuyHouse { private IBuyHouse target; public CustomerProxy(IBuyHouse buyHouse) { this.target = buyHouse; } public void Buy() { System.Console.WriteLine("篩選符合條件的房源"); this.target.Buy(); } } public class Program { static void Main(string[] args) { IBuyHouse buyHouse = new CustomerProxy(new Customer()); buyHouse.Buy(); System.Console.ReadKey(); } } }
動(dòng)態(tài)代理
namespace DynamicProxy { using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; /// <summary> /// 方法攔截器接口 /// </summary> public interface IMethodInterceptor { /// <summary> /// 調(diào)用攔截器 /// </summary> /// <param name="targetMethod">攔截的目標(biāo)方法</param> /// <param name="args">攔截的目標(biāo)方法參數(shù)列表</param> /// <returns>攔截的目標(biāo)方法返回值</returns> object Interceptor(MethodInfo targetMethod, object[] args); } /// <summary> /// 代理類生成器 /// </summary> public class ProxyFactory : DispatchProxy { private IMethodInterceptor _interceptor; /// <summary> /// 創(chuàng)建代理類實(shí)例 /// </summary> /// <param name="targetType">要代理的接口</param> /// <param name="interceptor">攔截器</param> /// <returns></returns> public static object CreateInstance(Type targetType, IMethodInterceptor interceptor) { object proxy = GetProxy(targetType); ((ProxyFactory)proxy).GetInterceptor(interceptor); return proxy; } /// <summary> /// 創(chuàng)建代理類實(shí)例 /// </summary> /// <param name="targetType">要代理的接口</param> /// <param name="interceptorType">攔截器</param> /// <param name="parameters">攔截器構(gòu)造函數(shù)參數(shù)值</param> /// <returns>代理實(shí)例</returns> public static object CreateInstance(Type targetType, Type interceptorType, params object[] parameters) { object proxy = GetProxy(targetType); ((ProxyFactory)proxy).GetInterceptor(interceptorType, parameters); return proxy; } /// <summary> /// 創(chuàng)建代理類實(shí)例 /// </summary> /// <typeparam name="TTarget">要代理的接口</typeparam> /// <typeparam name="TInterceptor">攔截器</typeparam> /// <param name="parameters">攔截器構(gòu)造函數(shù)參數(shù)值</param> /// <returns></returns> public static TTarget CreateInstance<TTarget, TInterceptor>(params object[] parameters) where TInterceptor : IMethodInterceptor { object proxy = GetProxy(typeof(TTarget)); ((ProxyFactory)proxy).GetInterceptor(typeof(TInterceptor), parameters); return (TTarget)proxy; } /// <summary> /// 獲取代理類 /// </summary> /// <param name="targetType"></param> /// <returns></returns> private static object GetProxy(Type targetType) { MethodCallExpression callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyFactory) }); return Expression.Lambda<Func<object>>(callexp).Compile()(); } /// <summary> /// 獲取攔截器 /// </summary> /// <param name="interceptorType"></param> /// <param name="parameters"></param> private void GetInterceptor(Type interceptorType, object[] parameters) { Type[] ctorParams = parameters.Select(x => x.GetType()).ToArray(); IEnumerable<ConstantExpression> paramsExp = parameters.Select(x => Expression.Constant(x)); NewExpression newExp = Expression.New(interceptorType.GetConstructor(ctorParams), paramsExp); this._interceptor = Expression.Lambda<Func<IMethodInterceptor>>(newExp).Compile()(); } /// <summary> /// 獲取攔截器 /// </summary> /// <param name="interceptor"></param> private void GetInterceptor(IMethodInterceptor interceptor) { this._interceptor = interceptor; } /// <summary> /// 執(zhí)行代理方法 /// </summary> /// <param name="targetMethod"></param> /// <param name="args"></param> /// <returns></returns> protected override object Invoke(MethodInfo targetMethod, object[] args) { return this._interceptor.Interceptor(targetMethod, args); } } /// <summary> /// 表演者 /// </summary> public interface IPerform { /// <summary> /// 唱歌 /// </summary> void Sing(); /// <summary> /// 跳舞 /// </summary> void Dance(); } /// <summary> /// 具體的表演者——?jiǎng)⒌氯A Andy /// </summary> public class AndyPerformer : IPerform { public void Dance() { System.Console.WriteLine("給大家表演一個(gè)舞蹈"); } public void Sing() { System.Console.WriteLine("給大家唱首歌"); } } /// <summary> /// 經(jīng)紀(jì)人——負(fù)責(zé)演員的所有活動(dòng) /// </summary> public class PerformAgent : IMethodInterceptor { public IPerform _perform; public PerformAgent(IPerform perform) { this._perform = perform; } public object Interceptor(MethodInfo targetMethod, object[] args) { System.Console.WriteLine("各位大佬,要我們家藝人演出清閑聯(lián)系我"); object result = targetMethod.Invoke(this._perform, args); System.Console.WriteLine("各位大佬,表演結(jié)束該付錢了"); return result; } } public class Program { static void Main(string[] args) { IPerform perform; //perform = ProxyFactory.CreateInstance<IPerform, PerformAgent>(new AndyPerformer()); //perform.Sing(); //perform.Dance(); ServiceCollection serviceDescriptors = new ServiceCollection(); serviceDescriptors.AddSingleton<IPerform>(ProxyFactory.CreateInstance<IPerform, PerformAgent>(new AndyPerformer())); IServiceProvider serviceProvider = serviceDescriptors.BuildServiceProvider(); perform = serviceProvider.GetService<IPerform>(); perform.Sing(); perform.Dance(); System.Console.ReadKey(); } } }
總結(jié)
- 使用拓展方法只能拓展新增方法,不能增強(qiáng)已有的功能
- 使用繼承類或接口,類只能單繼承,并且在父類改變后,所有的子類都要跟著變動(dòng)
- 使用代理模式與繼承一樣代理對(duì)象和真實(shí)對(duì)象之間的的關(guān)系在編譯時(shí)就確定了
- 使用裝飾者模式能夠在運(yùn)行時(shí)動(dòng)態(tài)地增強(qiáng)類的功能
參考引用
利用.NET Core類庫System.Reflection.DispatchProxy實(shí)現(xiàn)簡易Aop
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)我們的支持。
上一篇:C#結(jié)束Excel進(jìn)程的步驟教學(xué)
欄 目:C#教程
下一篇:C#使用EF連接PGSql數(shù)據(jù)庫的完整步驟
本文標(biāo)題:C#中增強(qiáng)類功能的幾種方式詳解
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/4967.html
您可能感興趣的文章
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并打開的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實(shí)現(xiàn)實(shí)體類與字符串互相轉(zhuǎn)換的方法
- 01-10C#實(shí)現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10Extjs4如何處理后臺(tái)json數(shù)據(jù)中日期和時(shí)間
- 01-10C#通過Semaphore類控制線程隊(duì)列的方法
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#中DataGridView常用操作實(shí)例小結(jié)
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10C#操作ftp類完整實(shí)例


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 04-02jquery與jsp,用jquery
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子