经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C#中关于增强类功能的几种方式
来源:cnblogs  作者:Alvin.Lee  时间:2018/12/27 9:52:32  对本文有异议

C#中关于增强类功能的几种方式

本文主要讲解如何利用C#语言自身的特性来对一个类的功能进行丰富与增强,便于拓展现有项目的一些功能。

拓展方法

扩展方法被定义为静态方法,通过实例方法语法进行调用。方法的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才可使用。

  1. namespace Extensions
  2. {
  3.  
  4.     public static class StringExtension
  5.     {
  6.         public static DateTime ToDateTime(this string source)
  7.         {
  8.             DateTime.TryParse(source, out DateTime result);
  9.             return result;
  10.         }
  11.     }
  12. }
注意:
  • 如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。

  • 在命名空间级别将扩展方法置于相应的作用范围内。例如,在一个名为 Extensions 的命名空间中具有多个包含扩展方法的静态类,则在使用这些拓展方法时,必须引用其命名空间 using Extensions

继承

继承 面向对象的一个特性,属于Is a 关系,比如说Student继承Person,则说明Student is a Person。子类可以通过重写父类的方法或添加新的方法来实现对父类的拓展。

  1. namespace Inherit
  2. {
  3.     public class Persion
  4.     {
  5.         public string Name { get; set; }
  6.  
  7.         public int Age { get; set; }
  8.  
  9.         public void Eat()
  10.         {
  11.             Console.WriteLine("吃饭");
  12.         }
  13.  
  14.         public void Sleep()
  15.         {
  16.             Console.WriteLine("睡觉");
  17.         }
  18.     }
  19.  
  20.     public class Student : Persion
  21.     {
  22.         public void Study()
  23.         {
  24.             Console.WriteLine("学习");
  25.         }
  26.  
  27.         public new void Sleep()
  28.         {
  29.             Console.WriteLine("做作业,复习功课");
  30.             base.Sleep();
  31.         }
  32.     }
  33. }
继承的缺点:
  • 父类的内部细节对子类是可见的

  • 子类与父类的继承关系在编译阶段就确定下来了,无法在运行时动态改变从父类继承方法的行为

  • 如果父类方法做了修改,所有的子类都必须做出相应的调整,子类与父类是一种高度耦合,违反了面向对象的思想。

组合

组合就是在设计类的时候把需要用到的类作为成员变量加入到当前类中。

组合的优缺点:
  • 优点:

    • 隐藏了被引用对象的内部细节

    • 降低了两个对象之间的耦合

    • 可以在运行时动态修改被引用对象的实例

  • 缺点:

    • 系统变更可能需要不停的定义新的类

    • 系统结构变复杂,不再局限于单个类

建议多使用组合,少用继承

装饰者模式

装饰者模式指在不改变原类定义及继承关系的情况跟下,动态的拓展一个类的功能,就是利用创建一个包装类(wrapper)来装饰(decorator)一个已有的类。

包含角色:
  • 被装饰者:

    • Component 抽象被装饰者

    • ConcreteComponent 具体被装饰者,Component的实现,在装饰者模式中装饰的就是这货。

  • 装饰者:

    • Decorator 装饰者 一般是一个抽象类并且作为Component的子类,Decorator必然会有一个成员变量用来存储Component的实例

    • ConcreateDecorator 具体装饰者 Decorator的实现

在装饰者模式中必然会有一个最基本,最核心,最原始的接口或抽象类充当component和decorator的抽象组件

实现要点:
  • 定义一个类或接口,并且让装饰者及被装饰者的都继承或实现这个类或接口

  • 装饰者中必须持有被装饰者的引用

  • 装饰者中对需要增强的方法进行增强,不需要增强的方法调用原来的业务逻辑

  1. namespace Decorator
  2. {
  3.  
  4.     /// <summary>
  5.     ///  Component 抽象者装饰者
  6.     /// </summary>
  7.     public interface IStudent
  8.     {
  9.         void Learn();
  10.     }
  11.  
  12.     /// <summary>
  13.     /// ConcreteComponent 具体被装饰者
  14.     /// </summary>
  15.     public class Student : IStudent
  16.     {
  17.         private string _name;
  18.         public Student(string name)
  19.         {
  20.             this._name = name;
  21.         }
  22.         public void Learn()
  23.         {
  24.             System.Console.WriteLine(this._name + "学习了以上内容");
  25.         }
  26.     }
  27.     /// <summary>
  28.     /// Decorator 装饰者
  29.     /// </summary>
  30.     public abstract class Teacher : IStudent
  31.     {
  32.         private IStudent _student;
  33.         public Teacher(IStudent student)
  34.         {
  35.             this._student = student;
  36.         }
  37.         public virtual void Learn()
  38.         {
  39.             this.Rest();
  40.             this._student.Learn();
  41.         }
  42.  
  43.         public virtual void Rest()
  44.         {
  45.             Console.WriteLine("课间休息");
  46.         }
  47.     }
  48.  
  49.     /// <summary>
  50.     /// ConcreteDecorator 具体装饰者
  51.     /// </summary>
  52.     public class MathTeacher : Teacher
  53.     {
  54.         private String _course;
  55.         public MathTeacher(IStudent student, string course) : base(student)
  56.         {
  57.             this._course = course;
  58.         }
  59.         public override void Learn()
  60.         {
  61.             System.Console.WriteLine("学习新内容:" + this._course);
  62.             base.Learn();
  63.         }
  64.         public override void Rest()
  65.         {
  66.             System.Console.WriteLine("课间不休息,开始考试");
  67.         }
  68.     }
  69.  
  70.     /// <summary>
  71.     /// ConcreteDecorator 具体装饰者
  72.     /// </summary>
  73.     public class EnlishTeacher : Teacher
  74.     {
  75.         private String _course;
  76.         public EnlishTeacher(IStudent student, string course) : base(student)
  77.         {
  78.             this._course = course;
  79.         }
  80.  
  81.         public override void Learn()
  82.         {
  83.             this.Review();
  84.             System.Console.WriteLine("学习新内容:" + this._course);
  85.             base.Learn();
  86.         }
  87.  
  88.         public void Review()
  89.         {
  90.             System.Console.WriteLine("复习英文单词");
  91.         }
  92.     }
  93.  
  94.     public class Program
  95.     {
  96.         static void Main(string[] args)
  97.         {
  98.             IStudent student = new Student("student");
  99.             student = new MathTeacher(student, "高数");
  100.             student = new EnlishTeacher(student, "英语");
  101.             student.Learn();
  102.         }
  103.     }
  104. }
装饰者模式优缺点:
  • 优点:

    • 装饰者与被装饰者可以独立发展,不会互相耦合

    • 可以作为继承关系的替代方案,在运行时动态拓展类的功能

    • 通过使用不同的装饰者类或不同的装饰者排序,可以得到各种不同的结果

  • 缺点:

    • 产生很多装饰者类

    • 多层装饰复杂

代理模式

代理模式就是给一个对象提供一个代理对象,并且由代理控制原对象的引用。

包含角色:
  • 抽象角色:抽象角色是代理角色和被代理角色的所共同继承或实现的抽象类或接口

  • 代理角色:代理角色是持有被代理角色引用的类,代理角色可以在执行被代理角色的操作时附加自己的操作

  • 被代理角色:被代理角色是代理角色所代理的对象,是真实要操作的对象


静态代理

动态代理涉及到反射技术相对静态代理会复杂很多,掌握好动态代理对AOP技术有很大帮助

  1. namespace Proxy
  2. {
  3.     /// <summary>
  4.     /// 共同抽象角色
  5.     /// </summary>
  6.     public interface IBuyHouse
  7.     {
  8.         void Buy();
  9.     }
  10.  
  11.     /// <summary>
  12.     /// 真实买房人,被代理角色
  13.     /// </summary>
  14.     public class Customer : IBuyHouse
  15.     {
  16.         public void Buy()
  17.         {
  18.             System.Console.WriteLine("买房子");
  19.         }
  20.     }
  21.  
  22.     /// <summary>
  23.     /// 中介-代理角色
  24.     /// </summary>
  25.     public class CustomerProxy : IBuyHouse
  26.     {
  27.         private IBuyHouse target;
  28.         public CustomerProxy(IBuyHouse buyHouse)
  29.         {
  30.             this.target = buyHouse;
  31.         }
  32.         public void Buy()
  33.         {
  34.             System.Console.WriteLine("筛选符合条件的房源");
  35.             this.target.Buy();
  36.         }
  37.     }
  38.  
  39.     public class Program
  40.     {
  41.         static void Main(string[] args)
  42.         {
  43.             IBuyHouse buyHouse = new CustomerProxy(new Customer());
  44.             buyHouse.Buy();
  45.             System.Console.ReadKey();
  46.         }
  47.     }
  48. }

动态代理

  1. namespace DynamicProxy
  2. {
  3.     using Microsoft.Extensions.DependencyInjection;
  4.     using System;
  5.     using System.Collections.Generic;
  6.     using System.Linq;
  7.     using System.Linq.Expressions;
  8.     using System.Reflection;
  9.  
  10.     /// <summary>
  11.     /// 方法拦截器接口
  12.     /// </summary>
  13.     public interface IMethodInterceptor
  14.     {
  15.         /// <summary>
  16.         /// 调用拦截器
  17.         /// </summary>
  18.         /// <param name="targetMethod">拦截的目标方法</param>
  19.         /// <param name="args">拦截的目标方法参数列表</param>
  20.         /// <returns>拦截的目标方法返回值</returns>
  21.         object Interceptor(MethodInfo targetMethod, object[] args);
  22.     }
  23.  
  24.     /// <summary>
  25.     /// 代理类生成器
  26.     /// </summary>
  27.     public class ProxyFactory : DispatchProxy
  28.     {
  29.         private IMethodInterceptor _interceptor;
  30.  
  31.         /// <summary>
  32.         /// 创建代理类实例
  33.         /// </summary>
  34.         /// <param name="targetType">要代理的接口</param>
  35.         /// <param name="interceptor">拦截器</param>
  36.         /// <returns></returns>
  37.         public static object CreateInstance(Type targetType, IMethodInterceptor interceptor)
  38.         {
  39.             object proxy = GetProxy(targetType);
  40.             ((ProxyFactory)proxy).GetInterceptor(interceptor);
  41.             return proxy;
  42.         }
  43.  
  44.         /// <summary>
  45.         /// 创建代理类实例
  46.         /// </summary>
  47.         /// <param name="targetType">要代理的接口</param>
  48.         /// <param name="interceptorType">拦截器</param>
  49.         /// <param name="parameters">拦截器构造函数参数值</param>
  50.         /// <returns>代理实例</returns>
  51.         public static object CreateInstance(Type targetType, Type interceptorType, params object[] parameters)
  52.         {
  53.             object proxy = GetProxy(targetType);
  54.             ((ProxyFactory)proxy).GetInterceptor(interceptorType, parameters);
  55.             return proxy;
  56.         }
  57.  
  58.  
  59.         /// <summary>
  60.         /// 创建代理类实例
  61.         /// </summary>
  62.         /// <typeparam name="TTarget">要代理的接口</typeparam>
  63.         /// <typeparam name="TInterceptor">拦截器</typeparam>
  64.         /// <param name="parameters">拦截器构造函数参数值</param>
  65.         /// <returns></returns>
  66.         public static TTarget CreateInstance<TTarget, TInterceptor>(params object[] parameters) where TInterceptor : IMethodInterceptor
  67.         {
  68.             object proxy = GetProxy(typeof(TTarget));
  69.             ((ProxyFactory)proxy).GetInterceptor(typeof(TInterceptor), parameters);
  70.             return (TTarget)proxy;
  71.         }
  72.  
  73.         /// <summary>
  74.         /// 获取代理类
  75.         /// </summary>
  76.         /// <param name="targetType"></param>
  77.         /// <returns></returns>
  78.         private static object GetProxy(Type targetType)
  79.         {
  80.             MethodCallExpression callexp = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyFactory) });
  81.             return Expression.Lambda<Func<object>>(callexp).Compile()();
  82.         }
  83.  
  84.         /// <summary>
  85.         /// 获取拦截器
  86.         /// </summary>
  87.         /// <param name="interceptorType"></param>
  88.         /// <param name="parameters"></param>
  89.         private void GetInterceptor(Type interceptorType, object[] parameters)
  90.         {
  91.             Type[] ctorParams = parameters.Select(=> x.GetType()).ToArray();
  92.             IEnumerable<ConstantExpression> paramsExp = parameters.Select(=> Expression.Constant(x));
  93.             NewExpression newExp = Expression.New(interceptorType.GetConstructor(ctorParams), paramsExp);
  94.             this._interceptor = Expression.Lambda<Func<IMethodInterceptor>>(newExp).Compile()();
  95.         }
  96.  
  97.         /// <summary>
  98.         /// 获取拦截器
  99.         /// </summary>
  100.         /// <param name="interceptor"></param>
  101.         private void GetInterceptor(IMethodInterceptor interceptor)
  102.         {
  103.             this._interceptor = interceptor;
  104.         }
  105.  
  106.         /// <summary>
  107.         /// 执行代理方法
  108.         /// </summary>
  109.         /// <param name="targetMethod"></param>
  110.         /// <param name="args"></param>
  111.         /// <returns></returns>
  112.         protected override object Invoke(MethodInfo targetMethod, object[] args)
  113.         {
  114.             return this._interceptor.Interceptor(targetMethod, args);
  115.         }
  116.     }
  117.  
  118.     /// <summary>
  119.     /// 表演者
  120.     /// </summary>
  121.     public interface IPerform
  122.     {
  123.         /// <summary>
  124.         /// 唱歌
  125.         /// </summary>
  126.         void Sing();
  127.  
  128.         /// <summary>
  129.         /// 跳舞
  130.         /// </summary>
  131.         void Dance();
  132.     }
  133.  
  134.     /// <summary>
  135.     /// 具体的表演者——刘德华 Andy
  136.     /// </summary>
  137.     public class AndyPerformer : IPerform
  138.     {
  139.         public void Dance()
  140.         {
  141.             System.Console.WriteLine("给大家表演一个舞蹈");
  142.         }
  143.  
  144.         public void Sing()
  145.         {
  146.             System.Console.WriteLine("给大家唱首歌");
  147.         }
  148.     }
  149.  
  150.     /// <summary>
  151.     /// 经纪人——负责演员的所有活动
  152.     /// </summary>
  153.     public class PerformAgent : IMethodInterceptor
  154.     {
  155.         public IPerform _perform;
  156.         public PerformAgent(IPerform perform)
  157.         {
  158.             this._perform = perform;
  159.         }
  160.         public object Interceptor(MethodInfo targetMethod, object[] args)
  161.         {
  162.             System.Console.WriteLine("各位大佬,要我们家艺人演出清闲联系我");
  163.             object result = targetMethod.Invoke(this._perform, args);
  164.             System.Console.WriteLine("各位大佬,表演结束该付钱了");
  165.             return result;
  166.         }
  167.     }
  168.  
  169.     public class Program
  170.     {
  171.         static void Main(string[] args)
  172.         {
  173.             IPerform perform;
  174.  
  175.             //perform = ProxyFactory.CreateInstance<IPerform, PerformAgent>(new AndyPerformer());
  176.             //perform.Sing();
  177.             //perform.Dance();
  178.  
  179.             ServiceCollection serviceDescriptors = new ServiceCollection();
  180.             serviceDescriptors.AddSingleton<IPerform>(ProxyFactory.CreateInstance<IPerform, PerformAgent>(new AndyPerformer()));
  181.             IServiceProvider serviceProvider = serviceDescriptors.BuildServiceProvider();
  182.             perform = serviceProvider.GetService<IPerform>();
  183.             perform.Sing();
  184.             perform.Dance();
  185.  
  186.             System.Console.ReadKey();
  187.         }
  188.     }
  189.  
  190. }

总结

  • 使用拓展方法只能拓展新增方法,不能增强已有的功能

  • 使用继承类或接口,类只能单继承,并且在父类改变后,所有的子类都要跟着变动

  • 使用代理模式与继承一样代理对象和真实对象之间的的关系在编译时就确定了

  • 使用装饰者模式能够在运行时动态地增强类的功能

参考引用

利用.NET Core类库System.Reflection.DispatchProxy实现简易Aop

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号