TypeBuilder - Adding attributes

感情迁移 提交于 2019-12-21 23:37:06

问题


I have a helper class that uses a TypeBuilder to construct a dynamic type. It is used as follows :

var tbh = new TypeBuilderHelper("MyType");
tbh.AddProperty<float>("Number", 0.0f);
tbh.AddProperty<string>("String", "defaultStringValue");
tbh.Close();

var i1 = tbh.CreateInstance();
var i2 = tbh.CreateInstance();

I now want to add support for property attributes (existing attribute types, not dynamically generated types), along the lines of :

public class TypeBuilderHelper
    {
        public void AddProperty<T>(string name, T defaultValue, params Attribute[] attributes)
        {
            // ...
        }
    }

public class SomeAttribute : Attribute
    {
        public SomeAttribute(float a) { }
        public SomeAttribute(float a, int b) { }
        public SomeAttribute(float a, double b, string c) { }
    }

 var tbh2 = new TypeBuilderHelper("MyType2");
 tbh2.AddProperty<float>("Number", 0.0f, new SomeAttribute(0.0f, 1));
 tbh2.AddProperty<string>("String", "defaultStringValue");
 tbh2.Close();

 var i3 = tbh.CreateInstance();
 var i4 = tbh.CreateInstance();

But I'm not sure how that would work. I'm creating the properties using the PropertyBuilder, but the CustomAttributeBuilder wants a constructor signature and the constructor args, where as all I'll have is an instance of a constructed Attribute.


回答1:


An instance of an attribute isn't helpful here you need to define the constructor and the values that should be called. A simple solution might be to change the AddProperty Signature and exchange the params Attribute Parameter with a params CustomAttributeBuilder Parameter and construct Builder instances instead of attributes.

var ci = typeof(SomeAttribute).GetConstructor(new Type[] { typeof(float), typeof(int) });
var builder = new CustomAttributeBuilder(ci, new object[] { 0.0f, 1 });


来源:https://stackoverflow.com/questions/30264032/typebuilder-adding-attributes

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