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

Attribute在运行期赋值?        }

Attribute在运行期赋值?        
foreach(Attribute attr in type.GetCustomAttributes(true))
{
Attribute在运行期赋值?            help 
= attr as HelpAttribute;
Attribute在运行期赋值?            
if(null != help)
{
Attribute在运行期赋值?                Console.WriteLine(help.Description);
Attribute在运行期赋值?                Console.ReadLine();
Attribute在运行期赋值?            }

Attribute在运行期赋值?        }

Attribute在运行期赋值?    }

Attribute在运行期赋值?}

Attribute在运行期赋值?[Help(
"The origin value")]
Attribute在运行期赋值?
public class TestAttribute
{
Attribute在运行期赋值?}

Attribute在运行期赋值?[AttributeUsage(AttributeTargets.Class
|AttributeTargets.Method,AllowMultiple = true,Inherited = true)]
Attribute在运行期赋值?
public class HelpAttribute : Attribute
{
Attribute在运行期赋值?    
public HelpAttribute(string Descrition_in)
{
Attribute在运行期赋值?        
this.description = Descrition_in;
Attribute在运行期赋值?    }

Attribute在运行期赋值?    
protected string description;
Attribute在运行期赋值?    
public string Description 
{
Attribute在运行期赋值?        
get 
{
Attribute在运行期赋值?            
return this.description;
Attribute在运行期赋值?                 
Attribute在运行期赋值?        }

Attribute在运行期赋值?        
set 
{
Attribute在运行期赋值?            
this.description = value;
Attribute在运行期赋值?        }

Attribute在运行期赋值?            
Attribute在运行期赋值?    }
    
Attribute在运行期赋值?}

Attribute在运行期赋值?


 

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

这段代码的运行结果是:

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

相关文章:

  • 2022-02-03
  • 2022-12-23
猜你喜欢
  • 2022-01-03
  • 2021-09-09
  • 2021-07-28
  • 2022-02-16
  • 2021-12-05
  • 2021-11-11
相关资源
相似解决方案