[英]Generate call to generic method in runtime
目標:在運行時生成這樣的方法:
public void InsertOnSubmit<T>(IQueryable<T> q, T o) where T : class, new()
{
(q as Table<T>).InsertOnSubmit(o);
}
我當前的代碼是:
var tb = mb.DefineType("DatabaseDataRepository");
// define & implement other methods, etc
/* Define InsertOnSubmit<> method */
var insertOnSubmitMethod = tb.DefineMethod("InsertOnSubmit",
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |
MethodAttributes.NewSlot);
var genericInput = insertOnSubmitMethod.DefineGenericParameters("T")[0];
genericInput.SetGenericParameterAttributes(GenericParameterAttributes.ReferenceTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint);
insertOnSubmitMethod.SetParameters(typeof(IQueryable<>).MakeGenericType(genericInput), genericInput);
insertOnSubmitMethod.SetReturnType(null);
/* Implement InsertOnSubmit<> method */
var saveMethodGen = insertOnSubmitMethod.GetILGenerator();
saveMethodGen.Emit(OpCodes.Ldarg_1); // push first argument (collection)
saveMethodGen.Emit(OpCodes.Isinst, typeof(Table<>).MakeGenericType(genericInput)); // cast first argument to Table<>
saveMethodGen.Emit(OpCodes.Ldarg_2); // push second argument (element)
saveMethodGen.Emit(OpCodes.Callvirt, typeof(Table<>).GetMethod("InsertOnSubmit")); // insert second argument to table
saveMethodGen.Emit(OpCodes.Ret); // return from InsertOnSubmit method
但是在生成的實例上運行此方法,我得到: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
,其堆棧at DatabaseDataRepository.InsertOnSubmit[T](IQueryable`1 , T )
我懷疑這行中有什么問題saveMethodGen.Emit(OpCodes.Callvirt, typeof(Table<>).GetMethod("InsertOnSubmit"));
-確實應該類似於typeof(Table<>).MakeGenericType(genericInput).GetMethod("InsertOnSubmit")
-但這會引發NotSupportedException
有什么解決的辦法嗎? 謝謝。
您必須使用靜態System.Reflection.Emit.Typebuilder.GetMethod
方法來創建正確鍵入的MethodInfo
。
msdn指出:
返回與通用類型定義的指定方法相對應的指定構造通用類型的方法。
您的情況是:
Typebuilder.GetMethod(typeof(Table<>).MakeGenericType(genericInput), typeof(Table<>).GetMethod("InsertOnSubmit"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.