在运行时更改属性的参数 [英] Change Attribute's parameter at runtime

查看:33
本文介绍了在运行时更改属性的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否可以在运行时更改属性的参数?例如,在一个程序集中,我有以下类

I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class

public class UserInfo
{
    [Category("change me!")]
    public int Age
    {
        get;
        set;
    }
    [Category("change me!")]
    public string Name
    {
        get;
        set;
    }
}

这是由第三方供应商提供的类,我无法更改代码.但是现在发现上面的描述不准确,想把上面的类的实例绑定到属性网格时,把change me"这个类名改成别的东西.

This is a class that is provided by a third party vendor and I can't change the code. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.

我可以知道怎么做吗?

推荐答案

好吧,你每天都在学习新东西,显然我撒谎了:

Well you learn something new every day, apparently I lied:

人们普遍没有意识到的是您可以公平地更改属性实例值在运行时很容易.原因是,当然,实例创建的属性类是完全正常的物体并且可以使用不受限制.例如,我们可以得到对象:

What isn’t generally realised is that you can change attribute instance values fairly easily at runtime. The reason is, of course, that the instances of the attribute classes that are created are perfectly normal objects and can be used without restriction. For example, we can get the object:

ASCII[] attrs1=(ASCII[])
    typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);

...更改其公共变量的值并显示它已更改:

…change the value of its public variable and show that it has changed:

attrs1[0].MyData="A New String";
MessageBox.Show(attrs1[0].MyData);

...最后创建另一个实例并证明其值不变:

…and finally create another instance and show that its value is unchanged:

ASCII[] attrs3=(ASCII[])
    typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
 MessageBox.Show(attrs3[0].MyData);

http://www.vsj.co.uk/articles/display.asp?id=713

这篇关于在运行时更改属性的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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