views:

47

answers:

1

Hi, 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
+3  A: 

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
Than you buddy. It worked with currGetIL.Emit(OpCodes.Ldc_I4, 25).Thanks a million.
Hitesh Sadarangani
Of course, you could reward the correct answer by marking it as accepted. ;-)
Rytmis