private static void GenerateProxyTypeFromProperties(Type sourceType, Type targetType, VerificationResult verificationResult) { var baseType = typeof(ProxyBase <>).MakeGenericType(sourceType); var typeBuilder = ProxyAssembly.DefineType( string.Format("Proxy_From_{0}_To_{1}", sourceType.Name, targetType.Name), TypeAttributes.Class, baseType, new Type[] { targetType }); var constructorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new Type[] { sourceType }); var il = constructorBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, sourceType); il.Emit(OpCodes.Call, baseType.GetTypeInfo() .DeclaredConstructors .First(c => { var parameters = c.GetParameters(); return(parameters.Length == 1 && parameters[0].ParameterType == sourceType); })); il.Emit(OpCodes.Ret); verificationResult.Constructor = constructorBuilder; verificationResult.TypeBuilder = typeBuilder; }
private static void GenerateProxyTypeForList( Type sourceElementType, Type targetElementType, Type proxyType, VerificationResult verificationResult) { var baseType = typeof(ProxyList <,>).MakeGenericType(sourceElementType, targetElementType); var baseConstructor = baseType.GetTypeInfo().DeclaredConstructors.FirstOrDefault(ctor => !ctor.IsPublic && !ctor.IsStatic); var typeBuilder = ProxyAssembly.DefineType( string.Format("Proxy_From_IList<{0}>_To_IReadOnlyList<{1}>", sourceElementType.Name, targetElementType.Name), TypeAttributes.Class, baseType, new Type[] { typeof(IReadOnlyList <>).MakeGenericType(targetElementType) }); var constructorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(IList <>).MakeGenericType(sourceElementType) }); var il = constructorBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); // LdToken loads a RuntimeTypeHandle, while the constructor takes a Type, so we convert. // This is the same strategy the compiler uses when constructing this class. il.Emit(OpCodes.Ldtoken, proxyType); var getTypeFromHandle = typeof(Type).GetRuntimeMethods() .First(m => string.Equals(m.Name, nameof(Type.GetTypeFromHandle)) && m.IsStatic && m.IsPublic); il.EmitCall(OpCodes.Call, getTypeFromHandle, null); il.Emit(OpCodes.Call, baseConstructor); il.Emit(OpCodes.Ret); verificationResult.Constructor = constructorBuilder; verificationResult.TypeBuilder = typeBuilder; }