C# Emit , how to write a if statement

风流意气都作罢 提交于 2019-12-23 17:15:04

问题


first of all , i have a class

    internal class Parent
    {
        protected void Write(string message, [CallerMemberName] string caller = null)
        {
            Console.WriteLine($"{caller} :: {message}");
        }
    }

and i want to dynamic create a class , the class has a property "Name", if the property value changed then call write method , looks like

    class Child : Parent
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (_name != value)
                {
                    Write("changedto: " + value);
                    _name = value;
                }
            }
        }
    }

what i want to know is the highlight clause. how to write it in emit. please help.


i want some code below

     private static MethodBuilder BuildSetter(TypeBuilder typeBuilder, PropertyInfo property, FieldBuilder fieldBuilder, MethodAttributes attributes)
    {
        var setterBuilder = typeBuilder.DefineMethod($"set_{property.Name}", attributes, null, new Type[] { property.PropertyType });
        var ilGenerator = setterBuilder.GetILGenerator();

        ilGenerator.Emit(OpCodes.Ldarg_0);  //this
        ilGenerator.Emit(OpCodes.Ldarg_1);  // the first one in arguments list

            //code should be here

        ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);
        ilGenerator.Emit(OpCodes.Ret);

        return setterBuilder;
    }

Updated

var typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public,typeof(PropertyChanged));


var t = typeof(PropertyChanged);

var m2 = t.GetMethod("ValueChanged");

you see , when i create the type , i use a Parent type , and in the parent type there is a method called "ValueChanged"

protected void ValueChanged(object value,[CallerMemberName] string property = null)

i want call it in set method.


update 2

private static MethodBuilder BuildSetter(TypeBuilder typeBuilder, PropertyInfo property, FieldBuilder fieldBuilder, MethodAttributes attributes)
{
    var propertyType = property.PropertyType;
    var setterBuilder = typeBuilder.DefineMethod($"set_{property.Name}", attributes, null, new Type[] { propertyType });

    var setIl = setterBuilder.GetILGenerator();
    Label exitSet = setIl.DefineLabel(); // define label to jump in case condition is false
    setIl.Emit(OpCodes.Ldarg_0); // this
    setIl.Emit(OpCodes.Ldfld, fieldBuilder); // _name field
    setIl.Emit(OpCodes.Ldarg_1); // value

    var inequality = propertyType.GetMethod("Equals", new[] { propertyType});
    setIl.Emit(OpCodes.Callvirt, inequality); // '!=' method
    setIl.Emit(OpCodes.Brtrue_S, exitSet); // check for inequality


    setIl.Emit(OpCodes.Ldarg_0); // load string literal
    setIl.Emit(OpCodes.Ldarg_1); // value
    setIl.Emit(OpCodes.Ldstr, property.Name);

    var m = typeBuilder.BaseType.GetMethod("ValueChanged", new Type[] {typeof(object),typeof(string) });

    setIl.Emit(OpCodes.Call, m);

    setIl.Emit(OpCodes.Ldarg_0); // this
    setIl.Emit(OpCodes.Ldarg_1); // value
    setIl.Emit(OpCodes.Stfld, fieldBuilder); // save the new value into _name
    setIl.MarkLabel(exitSet); // mark the label
    setIl.Emit(OpCodes.Ret); // return

    return setterBuilder;
}

update 3 screen-snaps


update 4

maybe , i have found the error reason , see Reflection Emit and Type Inheritance: Calling Base Type Constructors

update 5

finally , i got the error reason . it was not what i guessed at update 4 , it was caused by calling parent't method "ValueChanged" . before we transfer the parameter to the method , we should Box it as Object if the original data type is IsValueType . see the reference below ,

C# emit , type value compare


回答1:


@AlbertK answer shows you the right way, I'll add the complete code. Hope it will help.

I put everything in one method.. refactor it as you wish.

// define assembly and module
var propertyName = "Name";
var propertyType = typeof(string);
var ab = AssemblyBuilder.DefineDynamicAssembly(
            new AssemblyName("dynamicAssembly"), 
            AssemblyBuilderAccess.Save);
var mb = ab.DefineDynamicModule("dynamicModule", "dynamicModule.dll");

// define type, field and property
var tb = mb.DefineType("dynamicType");
var fb = tb.DefineField("_name", propertyType, FieldAttributes.Private);
var pb = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, Type.EmptyTypes);
var get = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
var set = tb.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType });

// write the IL for the get method
var getIl = get.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0); // this
getIl.Emit(OpCodes.Ldfld, fb); // _name field
getIl.Emit(OpCodes.Ret);

// write the IL for the set method
var setIl = set.GetILGenerator();
Label exitSet = setIl.DefineLabel(); // define label to jump in case condition is false
setIl.Emit(OpCodes.Ldarg_0); // this
setIl.Emit(OpCodes.Ldfld, fb); // _name field
setIl.Emit(OpCodes.Ldarg_1); // value
var inequality = propertyType.GetMethod("op_Inequality", new[] { propertyType, propertyType });
setIl.Emit(OpCodes.Call, inequality); // '!=' method
setIl.Emit(OpCodes.Brfalse_S, exitSet); // check for inequality
setIl.Emit(OpCodes.Ldstr, "changedto:"); // load string literal
setIl.Emit(OpCodes.Ldarg_1); // value
var concat = propertyType.GetMethod("Concat", new[] { propertyType, propertyType });
setIl.Emit(OpCodes.Call, concat); // concat two strings (literal + value)
var writeline = typeof(Console).GetMethod("WriteLine", new[] { propertyType });
setIl.Emit(OpCodes.Call, writeline); // write
setIl.Emit(OpCodes.Ldarg_0); // this
setIl.Emit(OpCodes.Ldarg_1); // value
setIl.Emit(OpCodes.Stfld, fb); // save the new value into _name
setIl.MarkLabel(exitSet); // mark the label
setIl.Emit(OpCodes.Ret); // return
pb.SetGetMethod(get);
pb.SetSetMethod(set);

tb.CreateType(); // complete the type
ab.Save("dynamicModule.dll"); // save the assembly to disk

And the result

internal class dynamicType
{
    private string _name;

    public string Name
    {
        get
        {
            return this._name;
        }
        set
        {
            if (this._name != value)
            {
                 Console.WriteLine("changedto:" + value);
                 this._name = value;
            }
        }
    }
}



回答2:


You can use a label, then you can jump to it using OpCodes.Beq that checks equality of two variables on the stack. Try this:

...

var toEnd = ilGenerator.DefineLabel();
ilGenerator.Emit(OpCodes.Beq, toEnd);

ilGenerator.Emit(OpCodes.Ldstr, "Changed");
ilGenerator.Emit(OpCodes.Call, 
    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);

ilGenerator.MarkLabel(toEnd);
ilGenerator.Emit(OpCodes.Ret);

It should be equivalent to:

if (_name != value)
{
    Console.WriteLine("Changed");
    _name = value;
}

Note: Before the emitting OpCodes.Beq you need to push onto stack two elements (value and _name field).

You can see more detailed code in Dudi Keleti's answer. He uses op_Inequality instead of OpCodes.Beq to jump to the target label.



来源:https://stackoverflow.com/questions/54646543/c-sharp-emit-how-to-write-a-if-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!