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;
}
}
}
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也是类,属性可能也是可写的,所以就做了以上测试。