您好,登錄后才能下訂單哦!
前言
本文主要講解如何利用C#語言自身的特性來對一個類的功能進行豐富與增強,便于拓展現有項目的一些功能。
拓展方法
擴展方法被定義為靜態方法,通過實例方法語法進行調用。方法的第一個參數指定該方法作用于哪個類型,并且該參數以 this 修飾符為前綴。僅當使用 using 指令將命名空間顯式導入到源代碼中之后,擴展方法才可使用。
namespace Extensions { public static class StringExtension { public static DateTime ToDateTime(this string source) { DateTime.TryParse(source, out DateTime result); return result; } } }
注意:
繼承
繼承 面向對象的一個特性,屬于Is a 關系,比如說Student繼承Person,則說明Student is a Person。子類可以通過重寫父類的方法或添加新的方法來實現對父類的拓展。
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("學習"); } public new void Sleep() { Console.WriteLine("做作業,復習功課"); base.Sleep(); } } }
繼承的缺點:
組合
組合就是在設計類的時候把需要用到的類作為成員變量加入到當前類中。
組合的優缺點:
優點:
缺點:
建議多使用組合,少用繼承
裝飾者模式
裝飾者模式指在不改變原類定義及繼承關系的情況跟下,動態的拓展一個類的功能,就是利用創建一個包裝類(wrapper)來裝飾(decorator)一個已有的類。
包含角色:
被裝飾者:
裝飾者:
在裝飾者模式中必然會有一個最基本,最核心,最原始的接口或抽象類充當component和decorator的抽象組件
實現要點:
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 + "學習了以上內容"); } } /// <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("學習新內容:" + 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("學習新內容:" + this._course); base.Learn(); } public void Review() { System.Console.WriteLine("復習英文單詞"); } } public class Program { static void Main(string[] args) { IStudent student = new Student("student"); student = new MathTeacher(student, "高數"); student = new EnlishTeacher(student, "英語"); student.Learn(); } } }
裝飾者模式優缺點:
優點:
缺點:
代理模式
代理模式就是給一個對象提供一個代理對象,并且由代理控制原對象的引用。
包含角色:
靜態代理
動態代理涉及到反射技術相對靜態代理會復雜很多,掌握好動態代理對AOP技術有很大幫助
namespace Proxy { /// <summary> /// 共同抽象角色 /// </summary> public interface IBuyHouse { void Buy(); } /// <summary> /// 真實買房人,被代理角色 /// </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(); } } }
動態代理
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> /// 調用攔截器 /// </summary> /// <param name="targetMethod">攔截的目標方法</param> /// <param name="args">攔截的目標方法參數列表</param> /// <returns>攔截的目標方法返回值</returns> object Interceptor(MethodInfo targetMethod, object[] args); } /// <summary> /// 代理類生成器 /// </summary> public class ProxyFactory : DispatchProxy { private IMethodInterceptor _interceptor; /// <summary> /// 創建代理類實例 /// </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> /// 創建代理類實例 /// </summary> /// <param name="targetType">要代理的接口</param> /// <param name="interceptorType">攔截器</param> /// <param name="parameters">攔截器構造函數參數值</param> /// <returns>代理實例</returns> public static object CreateInstance(Type targetType, Type interceptorType, params object[] parameters) { object proxy = GetProxy(targetType); ((ProxyFactory)proxy).GetInterceptor(interceptorType, parameters); return proxy; } /// <summary> /// 創建代理類實例 /// </summary> /// <typeparam name="TTarget">要代理的接口</typeparam> /// <typeparam name="TInterceptor">攔截器</typeparam> /// <param name="parameters">攔截器構造函數參數值</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> /// 執行代理方法 /// </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> /// 具體的表演者——劉德華 Andy /// </summary> public class AndyPerformer : IPerform { public void Dance() { System.Console.WriteLine("給大家表演一個舞蹈"); } public void Sing() { System.Console.WriteLine("給大家唱首歌"); } } /// <summary> /// 經紀人——負責演員的所有活動 /// </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("各位大佬,要我們家藝人演出清閑聯系我"); object result = targetMethod.Invoke(this._perform, args); System.Console.WriteLine("各位大佬,表演結束該付錢了"); 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(); } } }
總結
參考引用
利用.NET Core類庫System.Reflection.DispatchProxy實現簡易Aop
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。