首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >了解TypeDescriptor/PropertyDescriptor/等

了解TypeDescriptor/PropertyDescriptor/等
EN

Stack Overflow用户
提问于 2010-12-01 00:48:22
回答 1查看 2.7K关注 0票数 1

请参阅代码:

代码语言:javascript
复制
class DataItem
{
    public DataItem(int num, string s)
    {
        Number = num;
        Str = s;
    }
    public int Number { get; set; }
    public string Str { get; set; }
}

static void Main(string[] args)
{
    var data = new DataItem(2, "hi");

    var provider = TypeDescriptor.AddAttributes(typeof(DataItem),
                                               new SerializableAttribute());

    var another = provider.CreateInstance(null, typeof(DataItem), 
                                 new Type[] { typeof(int), typeof(string) }, 
                                 new object[] { 100, "hello" }) as DataItem;

    var newProperty = TypeDescriptor.CreateProperty(another.GetType(), "Str", 
                                      typeof(string), 
                                      new DescriptionAttribute("new property"));
    //newProperty.SetValue(another, "new one");

    Console.WriteLine(newProperty.GetValue(another));
    Console.Read();
}

我对代码有几个问题:

(1)我在DataItem的类型中添加了一个SerializableAttribute,这个“更改”应用到了什么地方?I‘t get this attribute by typeof(DataItem).GetCustomAttributes(true).It似乎更改并未应用于"essential DataItem",而是临时存储在TypeDescriptionProvider中?

(2)实例another是由提供者创建的(我们在其中添加了属性),我想现在这个变量与SerializableAttributed DataItem的构造函数创建的变量是相同的?即使我们仍然不能通过another.GetType().GetCustomAttributes获取属性。

(3)我认为更改临时存储在提供程序中的另一个原因是,我试图创建一个名称为Str、类型为string的属性,它实际上已经存在于DataItem中。代码将输出hello。如果我取消对SetValue方法的注释,输出将是new one。我有什么误解吗?

EN

回答 1

Stack Overflow用户

发布于 2010-12-01 00:59:05

属性被添加到实例(数据),而不是类型。你有没有尝试过TypeDescriptor.AddAttributes(typeof(DataItem))呢?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4316217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档