C#中增强类功能的几种方式详解

发布时间:2020-09-18 14:47:06 作者:Alvin.Lee
来源:脚本之家 阅读:145

前言

本文主要讲解如何利用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

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。

推荐阅读:
  1. C#中几种代码复用的方式
  2. python 进程的几种创建方式详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

增强 功能

上一篇:关于vue组件事件属性穿透详解

下一篇:python找出最大数的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》