I'm new to reflections. I need to create a class which inherits from a parent class. I need to create a readonly property. This property calls an existing function in the parent class by passing an argument 25.
Everything works fine, except that I am unable to pass the value 25 to the function being called. Below is the code that generates the class. Please assist. Thanks.
Public Shared Function GetDynamicClass() As Type
Dim asmName As New AssemblyName
asmName.Name = "MyAssm"
Dim asmBuilder As AssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly (asmName, AssemblyBuilderAccess.RunAndSave)
Dim mdlBuilder As ModuleBuilder = asmBuilder.DefineDynamicModule("MyDynModule")
Dim TypeBldr As TypeBuilder = mdlBuilder.DefineType("MyDynClass", TypeAttributes.[Public] Or TypeAttributes开发者_开发技巧.[Class])
TypeBldr.SetParent(GetType(MyParent))
Dim PropertyName As String = ""
Dim PropBldr As PropertyBuilder = Nothing
Dim GetSetAttr As MethodAttributes = Nothing
Dim currGetPropMthdBldr As MethodBuilder = Nothing
Dim currGetIL As ILGenerator = Nothing
Dim mi As MethodInfo = Nothing
PropertyName = "SurveyDate"
PropBldr = TypeBldr.DefineProperty(PropertyName, PropertyAttributes.None, GetType(Object), New Type() {GetType(Object)})
GetSetAttr = MethodAttributes.[Public] Or MethodAttributes.HideBySig
currGetPropMthdBldr = TypeBldr.DefineMethod("get_value", GetSetAttr, GetType(Object), Type.EmptyTypes)
currGetIL = currGetPropMthdBldr.GetILGenerator()
mi = GetType(MyParent).GetMethod("GetProgress")
currGetIL.DeclareLocal(GetType(Object))
currGetIL.Emit(OpCodes.Ldarg_0)
currGetIL.Emit(OpCodes.Ldc_I4_0)
currGetIL.Emit(OpCodes.Conv_I8)
currGetIL.Emit(OpCodes.Call, mi)
currGetIL.Emit(OpCodes.Ret)
PropBldr.SetGetMethod(currGetPropMthdBldr)
Return TypeBldr.CreateType
End Function
Suppose you changed this:
currGetIL.Emit(OpCodes.Ldc_I4_0)
currGetIL.Emit(OpCodes.Conv_I8)
into this:
currGetIL.Emit(OpCodes.Ldc_I4, 25)
currGetIL.Emit(OpCodes.Conv_I8)
LDC_I4_0 is an opcode that loads the value "0". LDC_I4, on the other hand, lets you specify the actual argument yourself.
(Caveat: untested, got this from reading the docs)
精彩评论