使用AssemblyBuilder构建复杂类型

时间:2018-05-30 23:10:16

标签: c# .net-core reflection.emit

我一直致力于small library to build very simple types dynamically using AssemblyBuilder。我可以构建一个类型,在其中添加属性。但我面临的问题是在给定动态生成类型的情况下添加属性,该类型也是使用此简单库生成的。在其他工作中,创建一个复杂的类型。我尝试在类型中添加名称空间,但我认为我的问题的根源是在创建父类型时不导入嵌套类型。

我如何创建类型和嵌套类型:

var token = "TestNameSpace";
var nestedType = Builders.CustomTypeBuilder.New(@namespace: token).AddProperty<string>("NestedProp").Compile();

var propertyName = "NestedProp";
var obj = Builders.CustomTypeBuilder.NewExtend<DummyClass>(@namespace: token)
    .AddProperty(propertyName, nestedType)
    .Instantiate<DummyClass>();

嵌套类型(或NestedProp)有点undefined(&#34;未解析......&#34;)。

enter image description here

图书馆背后的主要逻辑:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using CustomTypeBuilder.Extensions;
using static CustomTypeBuilder.Utilities.TypeUtility;

namespace CustomTypeBuilder
{
    /// <summary>
    /// Creates a new type dynamically
    /// </summary>
    public class CustomTypeGenerator
    {
        private readonly TypeBuilder _typeBuilder;

        private readonly Dictionary<string, Type> _properties;

        /// <summary>
        /// Initialize custom type builder
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentType"></param>
        /// <param name="namespace"></param>
        public CustomTypeGenerator(string name = null, Type parentType = null, string @namespace = null)
        {
            var assemblyName = RandomSafeString("DynamicAseembly");
            var typeSignature = name ?? RandomSafeString("DynamicType");

            // add namespace
            if (@namespace != name)
            {
                typeSignature = $"{@namespace}.{typeSignature}";
            }

            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule(RandomSafeString("Module"));
            _typeBuilder = moduleBuilder.DefineType(typeSignature,
                TypeAttributes.Public |
                TypeAttributes.Class |
                TypeAttributes.AutoClass |
                TypeAttributes.AnsiClass |
                TypeAttributes.BeforeFieldInit |
                TypeAttributes.AutoLayout,
                parentType);

            _typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            _properties = new Dictionary<string, Type>();
        }

        /// <summary>
        /// Add attribute to the class
        /// </summary>
        /// <param name="attribute"></param>
        public void AddAttribute(Attribute attribute)
        {
            _typeBuilder.SetCustomAttribute(attribute.BuildCustomAttribute());
        }

        /// <summary>
        /// Compile the type builder to a type
        /// </summary>
        /// <returns></returns>
        public Type CompileResultType()
        {            
            return _typeBuilder.CreateType();
        }

        /// <summary>
        /// Add interfaces to a type
        /// </summary>
        /// <param name="type"></param>
        public void AddInterface(Type type)
        {
            if (!type.IsInterface)
            {
                throw new ArgumentException("Type was expected to be an interface");
            }

            _typeBuilder.AddInterfaceImplementation(type);

            // add types in interface
            type.GetProperties().ForEach(x => AddProperty(x.Name, x.PropertyType));
        }

        public void ExtendType(Type type)
        {
            _typeBuilder.SetParent(type);
        }

        public void AddProperty(string propertyName, Type propertyType)
        {
            if (!IsValidName(propertyName)) throw new ArgumentException("Property name does not follow to C# type system");

            if (_properties.Keys.Any(x => x == propertyName)) throw new ArgumentException("Duplicate property name");

            // add property to dictionary
            _properties.Add(propertyName, propertyType);

            var fieldBuilder = _typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            var propertyBuilder = _typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            var getPropMthdBldr = _typeBuilder.DefineMethod("get_" + propertyName,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType,
                Type.EmptyTypes);
            var getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            var setPropMthdBldr = _typeBuilder.DefineMethod("set_" + propertyName,
                    MethodAttributes.Public |
                    MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig,
                    null, new[] {propertyType});

            var setIl = setPropMthdBldr.GetILGenerator();
            var modifyProperty = setIl.DefineLabel();
            var exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
    }
}

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:3)

虽然不完全是您问题的解决方案,但我希望这些信息有所帮助。

Visual Studio 2017和.NET Core 2.0的调试器似乎可以显示类型/对象。

Visual Studio Example 1

也可以正确设置和显示嵌套类型。

Visual Studio Example 2

它似乎也可以在VS Code中正常工作

VSCode Example

奇怪的是,在构造其他对象类型之前,当我们实例化并分配 var token = "TestNameSpace"; var nestedType = Builders.CustomTypeBuilder.New(@namespace: token).AddProperty<string>("NestedProp").Compile(); var propertyName = "NewProperty"; var someInstance = Activator.CreateInstance(nestedType); var obj = Builders.CustomTypeBuilder.NewExtend<DummyClass>(@namespace: token) .AddProperty(propertyName, nestedType) .Instantiate<DummyClass>(); var nestedValue = Activator.CreateInstance(nestedType); nestedType.GetProperty("NestedProp").SetValue(nestedValue, "NestedValue"); obj.GetType().GetProperty(propertyName).SetValue(obj, nestedValue); Debugger.Break(); 对象时,Rider调试器和.NET Core 2.0似乎能够正确识别嵌套属性类型使用它,但如果我们只是实例化它就不起作用。

e.g。

var token = "TestNameSpace";
var nestedType = Builders.CustomTypeBuilder.New(@namespace: token).AddProperty<string>("NestedProp").Compile();
var propertyName = "NewProperty";

// Instantiated, but not assigned to a local variable
Console.WriteLine(Activator.CreateInstance(nestedType));

var obj = Builders.CustomTypeBuilder.NewExtend<DummyClass>(@namespace: token)
    .AddProperty(propertyName, nestedType)
    .Instantiate<DummyClass>();

var nestedValue = Activator.CreateInstance(nestedType);

nestedType.GetProperty("NestedProp").SetValue(nestedValue, "NestedValue");
obj.GetType().GetProperty(propertyName).SetValue(obj, nestedValue);
Debugger.Break();

Rider example 1

VS

static Type CreateNestedType()
{
    var nestedType = Builders.CustomTypeBuilder.New(@namespace: "TestNameSpace")
                             .AddProperty<string>("NestedProp")
                             .Compile();

    var x = Activator.CreateInstance(nestedType);
    Console.WriteLine(x.GetType());
    // Toggling this line changes the behaviour of the debugger at the *next* breakpoint.
    //Debugger.Break();
    return nestedType;
}

static void Main(string[] args)
{
    var nestedType = CreateNestedType();
    var propertyName = "NewProperty";

    var obj = Builders.CustomTypeBuilder.NewExtend<DummyClass>(@namespace: "TestNameSpace")
        .AddProperty(propertyName, nestedType)
        .Instantiate<DummyClass>();

    var nestedValue = Activator.CreateInstance(nestedType);

    nestedType.GetProperty("NestedProp").SetValue(nestedValue, "NestedValue");
    obj.GetType().GetProperty(propertyName).SetValue(obj, nestedValue);
    Debugger.Break();
}

Rider example 2

但是,如果我们创建嵌套类型,实例化它并首先将它分配给一个单独范围内的变量,那么它似乎取决于调试器在分配后是否暂停。

e.g。

PEVerify

实际使用程序中的对象时,尽管在调试器中没有正确显示,但它们似乎表现正常。

当我使用.NET Framework而不是.NET Core编译和保存动态程序集时,它们都通过了Map

当我们在同一动态程序集/模块中定义两种类型而不是为每种类型使用新的动态程序集时,Rider似乎处理了上述所有情况。

基于所有这些看起来似乎有理由这是一个问题/错误/缺少功能/缺点(无论你想称之为什么)在Rider的调试器中,你可能想直接用JetBrains来提升它如果他们能够对这种情况有所了解。