2017-10-15 148 views
0

寻找解决办法,如何在实例构造函数中指定我在RT中动态创建的支持字段的属性。签名与编译器生成的属性匹配为自动属性。基本上它们将等同于下面列出的代码。通过反射发射在构造函数中分配字段

使用.NET核2.0

问:我如何分配使用发射构造函数中的支持字段?

例如:

public class MyClass { 
    public MyClass(int f1, string f2) { 
    _field1 = f1; 
    _field2 = f2; 
    } 

    private readonly int _field1; 
    private readonly string _field2; 

    public int Field1 { get; } 
    public string Field2 { get; } 
} 

private static void CreateConstructor(TypeBuilder typeBuilder, IReadOnlyList<dynamic> backingFields) { 
    var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new[] {typeof(KeyValuePair<string, string>), typeof(Dictionary<string, Type>)}); 
    var ctorIL = constructorBuilder.GetILGenerator(); 

    // Load the current instance ref in arg 0, along 
    // with the value of parameter "x" stored in arg X, into stfld. 

    for (var x = 0; x < backingFields.Count; x++) { 
    ctorIL.Emit(OpCodes.Ldarg_0); 
    ctorIL.Emit(OpCodes.Ldarg_S, x+1); 
    ctorIL.Emit(OpCodes.Stfld, backingFields[x]); 
    } 

    ctorIL.Emit(OpCodes.Ret); 
} 

public .cctor(KeyValuePair<string, string> kvp, Dictionary<string, Type> collection) { 
    _Name = kvp.Key; 
    _JSON = kvp.Value; 
    _PropertyInfo = collection; 
    } 

遍历接口中定义的方法,并在新类型创建一个新的属性&存取瓦特/私人设置器。

public interface IComplexType { 
    string Name { get; set; } 
    string JSON { get; set; } 
    object PropertyInfo { get; set; } 
    } 
+0

代码DOM是显著比Refection Emit更容易 – MickyD

+1

您发布的代码似乎将构造函数参数分配给后备字段。它不工作? –

+0

有些东西不能正常工作。它编译并返回类型。能够创建一个实例..检查时,我缺少一些字段/属性。例如,我应该有一个包含3个字段的Interface类。 JSON会将附加的字段/属性/方法附加到工作的类中,但我试图使界面中的成员只能读取。 public interface IComplexType {Name} {get;组; } string JSON {get;组; } [Bindable(true)] [TypeConverter(typeof(StringConverter))] object PropertyInfo {get;组; } } – Latency

回答

1

已解决!

需要更改构造函数参数以匹配迭代次数,因为它很难将Ldarg_1设置为KeyValuePair并分别为其分配Key & Value。

通过消除KVP并提供构造函数定义的附加参数如下:

var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new[] {typeof(string), typeof(string), typeof(Dictionary<string, Type>)}); 
    var ctorIl = constructorBuilder.GetILGenerator(); 

    for (var x = 0; x < backingFields.Count; x++) { 
    ctorIl.Emit(OpCodes.Ldarg_0); 
    ctorIl.Emit(OpCodes.Ldarg_S, x + 1); 
    ctorIl.Emit(OpCodes.Stfld, backingFields[x]); 
    } 

    ctorIl.Emit(OpCodes.Ret); 

要调用,我只是提取KVP这里的内容:

return (T) Activator.CreateInstance(TypeCollection[type], kvp.Key, kvp.Value, collection);