生成IL Upcodes以将值插入字典

时间:2014-10-11 15:51:50

标签: c# .net

给出以下课程

public class OgrEntity 
{
    public OgrEntity()
    {
        Properties = new Dictionary<string, object>();
    }
    public DbGeometry ogr_geometry { get; set; }
    public int ogr_fid { get; set; }

    public Dictionary<string, object> Properties;

}

我正在尝试在继承上述类作为其基础的类上创建动态属性。

    public static TypeBuilder CreateTypeBuilder<T>(
        string assemblyName, string moduleName, string typeName)
    {
        TypeBuilder typeBuilder = AppDomain
            .CurrentDomain
            .DefineDynamicAssembly(new AssemblyName(assemblyName),
                                   AssemblyBuilderAccess.Run)
            .DefineDynamicModule(moduleName)
            .DefineType(typeName, TypeAttributes.Public,typeof(T));
        typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

        return typeBuilder;
    }
    public static void CreateDictionaryWrappingProperty(TypeBuilder builder, string propertyName, Type propertyType)
    {

        const string SetterPrefix = "set_";

        // Dictionary to store.
        var dictType = typeof(Dictionary<string, object>);
        var dict = typeof(OgrEntity).GetProperty("Properties");
        var addMethod = dictType.GetMethod("Add");

        // Generate the property
        PropertyBuilder propertyBuilder = builder.DefineProperty(
            propertyName, PropertyAttributes.HasDefault, propertyType, null);

        // Property getter and setter attributes.
        MethodAttributes propertyMethodAttributes =
            MethodAttributes.Public | MethodAttributes.SpecialName |
            MethodAttributes.HideBySig;

        // Define the setter method.
        MethodBuilder setterMethod = builder.DefineMethod(
            string.Concat(SetterPrefix, propertyName),
            propertyMethodAttributes, null, new Type[] { propertyType });

        ILGenerator setterILCode = setterMethod.GetILGenerator();

       //What IL code do i need to do the following method:
       //set{ this.Properties.Add(propertyName,value); }

       //What IL code is need to do the getter
       //get{ if(this.Properties.ContainsKey(propertyName))
       //           return this.Properties[propertyName] //Cast to right type also;
       //       return null;
       //  }


        propertyBuilder.SetSetMethod(setterMethod);
    }

测试:

TypeBuilder builder = Program.CreateTypeBuilder<OgrEntity>(
            "MyDynamicAssembly", "MyModule", "MyType");
Program.CreateDictionaryWrappingProperty(builder, "uuid", typeof(string));
Type resultType = builder.CreateType();

1 个答案:

答案 0 :(得分:0)

编译符合您需要的C#代码。反汇编生成的二进制文件。这将教你需要发出什么操作码。