目标框架.Net Standard 2.0
安装引用类库System.Reflection.Emit 4.3.0
其他目标框架均适自带此类库,无需安装引用类库
原理:使用反射获取类、方法,将实现的代理类Invoke 通过System.Reflection.Emit改写到需要被改写的接口中,生成继承业务接口的中间类,调用中间类的接口则实现代理的任务。
/// <summary>
/// 对应java的InvocationHandler接口
/// 使用上应该是差不多的
/// 注意点是,因为C#的Property的getset也是走这一个方法的
/// 对于接口来说是全部代理,但是对于类只有虚方法代理
/// </summary>
public interface IInvocationHandler
{
object Invoke(object proxy, MethodInfo method, object[] args);
}
public interface myIInvocationHandler
{
object m(string args, string arg2);
}
public class II : IInvocationHandler
{
public object Invoke(object proxy, MethodInfo method, object[] args)
{
foreach (object o in args)
{
Console.WriteLine(o.ToString());
}
Console.WriteLine($"hahahaha");
return args[1];
}
}
/// <summary>
/// 缓存类,可以无视
/// </summary>
class ProxyTypeInfo
{
public TypeBuilder TypeBuilder;
public int Count;
public MethodInfo[] MethodInfos;
}
/// <summary>
/// 代理类
/// </summary>
public static class DynamicProxy
{
private static readonly string AssemblyName = "DynamicProxyAssembly";
private static readonly string ModuleName = "DynamicProxyModule";
private static readonly string TypeName = "DynamicProxy";
/// <summary>
/// 因为有些方法的指令是需要拆箱装箱的
/// </summary>
private static readonly HashSet<Type> CanBox = new HashSet<Type>
{
typeof(int), typeof(uint),
typeof(short), typeof(ushort),
typeof(long), typeof(ulong),
typeof(float), typeof(double),
typeof(sbyte), typeof(byte),
typeof(char),
typeof(decimal),
};
private static readonly Dictionary<Type, ProxyTypeInfo> ProxyDict = new Dictionary<Type, ProxyTypeInfo>();
private static TypeBuilder CreateDynamicTypeBuilder(Type type, Type parent, Type[] interfaces)
{
if (ProxyDict.TryGetValue(type, out var info))
{
info.Count++;
}
else
{
ProxyDict[type] = info = new ProxyTypeInfo
{
Count = 1
};
}
//AssemblyBuilder ab =
// AssemblyBuilder.DefineDynamicAssembly(
// aName,
// AssemblyBuilderAccess.Run);
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(AssemblyName + type.Name),
AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(ModuleName + type.Name);
return info.TypeBuilder = moduleBuilder.DefineType(TypeName + type.Name + info.Count,
TypeAttributes.Public | TypeAttributes.Class, parent, interfaces);
}
private static void ProxyInit(Type type, TypeBuilder typeBuilder, MethodInfo[] methodInfos,
MethodInfo handlerInvokeMethodInfo)
{
//定义两个字段
var handlerFieldBuilder =
typeBuilder.DefineField("_handler", typeof(IInvocationHandler), FieldAttributes.Private);
var methodInfosFieldBuilder =
typeBuilder.DefineField("_methodInfos", typeof(MethodInfo), FieldAttributes.Private);
//定义构造函数
var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard,
new[] { typeof(IInvocationHandler), typeof(MethodInfo[]) });
var ilCtor = constructorBuilder.GetILGenerator();
ilCtor.Emit(OpCodes.Ldarg_0);
ilCtor.Emit(OpCodes.Call,
typeof(object).GetConstructor(new Type[0]) ?? throw new Exception("不可能的错误:object.GetConstructor"));
ilCtor.Emit(OpCodes.Ldarg_0);
ilCtor.Emit(OpCodes.Ldarg_1);
ilCtor.Emit(OpCodes.Stfld, handlerFieldBuilder);
ilCtor.Emit(OpCodes.Ldarg_0);
ilCtor.Emit(OpCodes.Ldarg_2);
ilCtor.Emit(OpCodes.Stfld, methodInfosFieldBuilder);
ilCtor.Emit(OpCodes.Ret);
for (var i = 0; i < methodInfos.Length; i++)
{
var methodInfo = methodInfos[i];
var parameterTypes = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray();
var methodBuilder = typeBuilder.DefineMethod(methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
methodInfo.CallingConvention, methodInfo.ReturnType, parameterTypes);
var ilMethod = methodBuilder.GetILGenerator();
ilMethod.Emit(OpCodes.Ldarg_0);
ilMethod.Emit(OpCodes.Ldfld, handlerFieldBuilder);
ilMethod.Emit(OpCodes.Ldarg_0);
ilMethod.Emit(OpCodes.Ldarg_0);
ilMethod.Emit(OpCodes.Ldfld, methodInfosFieldBuilder);
ilMethod.Emit(OpCodes.Ldc_I4, i);
ilMethod.Emit(OpCodes.Ldelem_Ref);
ilMethod.Emit(OpCodes.Ldc_I4, parameterTypes.Length);
ilMethod.Emit(OpCodes.Newarr, typeof(object));
for (var j = 0; j < parameterTypes.Length; j++)
{
ilMethod.Emit(OpCodes.Dup);
ilMethod.Emit(OpCodes.Ldc_I4_S, (short)j);
ilMethod.Emit(OpCodes.Ldarg_S, (short)(j + 1));
if (CanBox.Contains(parameterTypes[j]))
{
ilMethod.Emit(OpCodes.Box, parameterTypes[j]);
}
ilMethod.Emit(OpCodes.Stelem_Ref);
}
ilMethod.Emit(OpCodes.Callvirt, handlerInvokeMethodInfo);
ilMethod.Emit(CanBox.Contains(methodInfo.ReturnType) ? OpCodes.Unbox_Any : OpCodes.Castclass,
methodInfo.ReturnType);
ilMethod.Emit(OpCodes.Ret);
}
}
/// <summary>
/// 通过接口创建动态代理
/// </summary>
public static T CreateProxyByInterface<T>(IInvocationHandler handler, bool userCache = true)
{
return (T)CreateProxyByInterface(typeof(T), handler, userCache);
}
public static object CreateProxyByInterface(Type type, IInvocationHandler handler, bool userCache = true)
{
if (!userCache || !ProxyDict.TryGetValue(type, out var info))
{
var handlerInvokeMethodInfo = typeof(IInvocationHandler).GetMethod("Invoke") ??
throw new Exception("不可能的错误:handlerInvokeMethodInfo");
var typeBuilder = CreateDynamicTypeBuilder(type, null, new[] { type });
var methodInfos = type.GetMethods();
ProxyInit(type, typeBuilder, methodInfos, handlerInvokeMethodInfo);
info = ProxyDict[type];
if (info.Count == 1)
{
info.MethodInfos = methodInfos;
}
}
//Type t = info.TypeBuilder.CreateTypeInfo();
return Activator.CreateInstance(info.TypeBuilder.CreateTypeInfo(), handler, info.MethodInfos) ??
throw new Exception("不同环境此处可能需要改写");
}
/// <summary>
/// 通过类创建动态代理
/// </summary>
public static T CreateProxyByType<T>(IInvocationHandler handler, bool userCache = true)
{
return (T)CreateProxyByType(typeof(T), handler, userCache);
}
public static object CreateProxyByType(Type type, IInvocationHandler handler, bool userCache = true)
{
if (!userCache || !ProxyDict.TryGetValue(type, out var info))
{
var handlerInvokeMethodInfo = typeof(IInvocationHandler).GetMethod("Invoke") ??
throw new Exception("不可能的错误:handlerInvokeMethodInfo");
var typeBuilder = CreateDynamicTypeBuilder(type, type, null);
var methodInfos = type.GetMethods().Where(methodInfo => methodInfo.IsVirtual || methodInfo.IsAbstract)
.ToArray();
ProxyInit(type, typeBuilder, methodInfos, handlerInvokeMethodInfo);
info = ProxyDict[type];
if (info.Count == 1)
{
info.MethodInfos = methodInfos;
}
}
return Activator.CreateInstance(info.TypeBuilder.CreateTypeInfo(), handler, info.MethodInfos) ??
throw new Exception("不同环境此处可能需要改写");
}
}
网友评论