Attribute在运行期赋值

Attribute在运行期赋值?

using  System;
using  System.Reflection;

public   class  test
{
    
public static void Main()
    
{
        TestAttribute ta 
= new TestAttribute();
        Type type 
= ta.GetType();
        HelpAttribute help;
        
foreach(Attribute attr in type.GetCustomAttributes(true))
        
{
            help 
= attr as HelpAttribute;
            
if(null != help)
            
{
                Console.WriteLine(help.Description);
                help.Description 
= "the value has changed.";
                Console.WriteLine(help.Description);
                Console.ReadLine();
            }

        }

        
foreach(Attribute attr in type.GetCustomAttributes(true))
        
{
            help 
= attr as HelpAttribute;
            
if(null != help)
            
{
                Console.WriteLine(help.Description);
                Console.ReadLine();
            }

        }

    }

}

[Help(
" The origin value " )]
public   class  TestAttribute
{
}

[AttributeUsage(AttributeTargets.Class
| AttributeTargets.Method,AllowMultiple  =   true ,Inherited  =   true )]
public   class  HelpAttribute : Attribute
{
    
public HelpAttribute(string Descrition_in)
    
{
        
this.description = Descrition_in;
    }

    
protected string description;
    
public string Description 
    
{
        
get 
        
{
            
return this.description;
                 
        }

        
set 
        
{
            
this.description = value;
        }

            
    }
    
}


 

运行一下以上代码,就可知道答案是否定的,

这段代码的运行结果是:

The origin value

the value has changed

The origin value

可以看出Attribute像一般的类一样可以更改它的值,只是更改的不是attach在TestAttribute类的那个实体,我测想(反射、装配件这些我才刚开始研究)Reflect把attach在TestAttribute类的Attibute类实体拿出来读值,而写Attribute值的时候创建了另一个Attribute的实体,以上只是我的测想,绝对有误,请高手指正。哎,一定要去学学IL,看反汇编出来的代码,看看.net是怎么工作的。

早几天在CSDN上看到一个网友的贴子,问做一个控件,可不可以一个属性更变,影响其它属性的显示与否,这个显示不显示是用[Browsable(false)]来控制的,我当时根据经验回答说不可以,这个是一描述就定了的,后来想想Attribute也是类,属性可能也是可写的,所以就做了以上测试。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值