0

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
Rich Schuler
  • 41,814
  • 6
  • 72
  • 59
  • 2
    You can simply write in c# what you want code do then compile and open assembly with reflector and select IL disassembler. – Sergey Mirvoda Dec 29 '09 at 07:35

1 Answers1

5

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)

Rytmis
  • 31,467
  • 8
  • 60
  • 69
  • Than you buddy. It worked with currGetIL.Emit(OpCodes.Ldc_I4, 25). Thanks a million. –  Dec 29 '09 at 09:44