TypeBuilder-添加属性 [英] TypeBuilder - Adding attributes

查看:102
本文介绍了TypeBuilder-添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用TypeBuilder构造动态类型的帮助程序类。它的用法如下:

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();

但是我不确定这将如何工作。我正在使用PropertyBuilder创建属性,但是CustomAttributeBuilder需要构造函数签名和构造函数args,因为我所拥有的只是构造属性的实例。

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.

推荐答案

在这里,属性实例无济于事,您需要定义构造函数和应调用的值。一个简单的解决方案可能是更改AddProperty签名,并使用params CustomAttributeBuilder参数交换params属性参数,并构造Builder实例而不是属性。

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 });

这篇关于TypeBuilder-添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆