简体   繁体   English

C#动态方法-具有“对象”返回类型的字段获取器

[英]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: 这是该方法的IL:

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 多亏了在线C#到IL工具,如果字段是值类型,我必须添加

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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