简体   繁体   中英

C# dynamic method - Field getter with “Object” return type

i need to get the field as type of "object".

This is the IL of the method:

gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
gen.Emit(OpCodes.Ret);

What should i add to cast to object.

Thanks to online C# to IL tools if field was value type i must add

OpCodes.Box

but what if field wasn't value type.

should i get field type and create two seperate dynamic method for reference type fields and value type fields.

Another question :

how can i destroy dynamic method and recreate it. (life cycle?)

You need to box value type results, for instance:

public void EmitFieldGetter(ILGenerator gen, FieldInfo field)
{
    gen.Emit(OpCodes.Ldarg_0);
    gen.Emit(OpCodes.Ldfld, field);

    if (field.FieldType.IsValueType)
    {
        gen.Emit(OpCodes.Box, field.FieldType);
    }

    gen.Emit(OpCodes.Ret);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM