C# 中一些类关系的判定方法 C#中关于增强类功能的几种方式 Asp.Net Core 轻松学-多线程之取消令牌
1. IsAssignableFrom实例方法 判断一个类或者接口是否继承自另一个指定的类或者接口。
public interface IAnimal { } public interface IDog : IAnimal { } public class Dog : IDog { } public class Cate : IAnimal { } public class Parrot { }
var iAnimalType = typeof(IAnimal); var iDogType = typeof(IDog); var dogType = typeof(Dog); var cateType = typeof(Cate); var parrotType = typeof(Parrot); Console.WriteLine(iAnimalType.IsAssignableFrom(iDogType) ? $"{iDogType.Name} was inherited from {iAnimalType.Name}" : $"{iDogType.Name} was not inherited from {iAnimalType.Name}"); Console.WriteLine(iAnimalType.IsAssignableFrom(dogType) ? $"{dogType.Name} was inherited from {iAnimalType.Name}" : $"{dogType.Name} was not inherited from {iAnimalType.Name}"); Console.WriteLine(iDogType.IsAssignableFrom(dogType) ? $"{dogType.Name} was inherited from {iDogType.Name}" : $"{dogType.Name} was not inherited from {iDogType.Name}"); Console.WriteLine(iAnimalType.IsAssignableFrom(cateType) ? $"{cateType.Name} was inherited from {iAnimalType.Name}" : $"{cateType.Name} was not inherited from {iAnimalType.Name}"); Console.WriteLine(iAnimalType.IsAssignableFrom(parrotType) ? $"{parrotType.Name} inherited from {iAnimalType.Name}" : $"{parrotType.Name} not inherited from {iAnimalType.Name}"); Console.ReadKey();
输出结果:
IDog was inherited from IAnimal
Dog was inherited from IAnimal
Dog was inherited from IDog
Cate was inherited from IAnimal
Parrot not inherited from IAnimal
2.IsInstanceOfType 判断某个对象是否继承自指定的类或者接口
Dog d=new Dog(); var result=typeof(IDog).IsInstanceOfType(d); Console.WriteLine(result? $"Dog was inherited from IDog": $"Dog was not inherited from IDog"); Console.ReadKey();
输出结果:
Dog was inherited from IDog
3.IsSubclassOf 判断一个对象的类型是否继承自指定的类,不能用于接口的判断,这能用于判定类的关系
public interface IAnimal { } public interface IDog : IAnimal { } public class Dog : IDog { } public class Husky : Dog { } public class Cate : IAnimal { } public class Parrot { }
Husky husky = new Husky(); var result = husky.GetType().IsSubclassOf(typeof(Dog)); Console.WriteLine(result ? $"Husky was inherited from Dog" : $"Husky was not inherited from Dog");
输出结果:
Husky was inherited from Dog
这个方法不能用于接口,如果穿接口进去永远返回的都是false
Dog dog = new Dog(); var dogResult = dog.GetType().IsSubclassOf(typeof(IDog)); Console.WriteLine(dogResult);
结果:
false
C#中关于增强类功能的几种方式
C#中关于增强类功能的几种方式
本文主要讲解如何利用C#语言自身的特性来对一个类的功能进行丰富与增强,便于拓展现有项目的一些功能。
拓展方法
扩展方法被定义为静态方法,通过实例方法语法进行调用。方法的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才可使用。
namespace Extensions
{
public static class StringExtension
{
public static DateTime ToDateTime(this string source)
{
DateTime.TryParse(source, out DateTime result);
return result;
}
}
}
注意:
- 如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。
- 在命名空间级别将扩展方法置于相应的作用范围内。例如,在一个名为 Extensions 的命名空间中具有多个包含扩展方法的静态类,则在使用这些拓展方法时,必须引用其命名空间 using Extensions
继承
继承 面向对象的一个特性,属于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 抽象被装饰者,
- ConcreteComponent 具体被装饰者,Component的实现,在装饰者模式中装饰的就是这货。
- 装饰者:
- Decorator 装饰者 一般是一个抽象类并且作为Component的子类,Decorator必然会有一个成员变量用来存储Component的实例
- ConcreateDecorator 具体装饰者 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>