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

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

问题描述

我不知道是否有可能在运行时改变属性的参数?例如,一个组件内我有下面的类

 公共类的UserInfo
{
    [类别(改变我!)]
    公众诠释年龄
    {
        得到;
        组;
    }
    [类别(改变我!)]
    公共字符串名称
    {
        得到;
        组;
    }
}

这是由第三方供应商和我无法改变code 提供的类。但是现在我发现,上面的描述是不准确的,我想以改变我一类的名称更改为别的东西,当我上面的类的实例绑定到属性网格。

我想知道如何做到这一点?


解决方案

那么你每天都学到新的东西,显然我撒谎了:


  

什么是不普遍意识到的是,
  你可以改变属性的实例值相当
  在运行时轻松。其原因是,
  当然,该的实例
  属性创建的类
  完全正常的对象,可以是
  无限制使用。例如,
  我们可以得到对象:

  ASCII [] = attrs1(ASCII [])
    typeof运算(MyClass的).GetCustomAttributes(typeof运算(ASCII),FALSE);


  
  

...改变其公共变量的值,并表明它已经改变:

  attrs1 [0] .MyData =一个新的字符串;
MessageBox.Show(attrs1 [0] .MyData);


  
  

...终于创建另一个实例
  并表明它的价值是不变的:

  ASCII [] = attrs3(ASCII [])
    typeof运算(MyClass的).GetCustomAttributes(typeof运算(ASCII),FALSE);
 MessageBox.Show(attrs3 [0] .MyData);


<一个href=\"http://www.vsj.co.uk/articles/display.asp?id=713\">http://www.vsj.co.uk/articles/display.asp?id=713

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

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.

May I know how to do this?

解决方案

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天全站免登陆