永久关闭

有了开始就有了好兆头,接受新生活也就是接受挑战。
我是一个普通的程序员,在这里开始写下程序人生的苦辣酸甜。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  1.        创建一个System.Attribute的子类

[AttributeUsage(    AttributeTargets.Class | AttributeTargets.Method,    //指定可应用于那些类型,如.Class, .Method, All等
AllowMultipe = true,    //允许应用多次
Inherited = false        //不继承到派生类
)]
public class SampleAttribute : System.Attribute
{
    
private string descr;
    
private string author;
    
private string title;
    
public string Descr
{
    
get {return descr;}
    
set {descr = value;}
}

public string Author
{
    
get {return author ;}
    
set {author = value ;}
}

public string Title
{
    
get {return title ;}
    
set {title = value ;}
}

//构造方法
Public SampleAttribute (string description)
{
    descr 
= description;
}

}

在创建子类时,可以为该类标注上AttributeUsage特性. 同时指定新定义的自定义特性可以应用于哪些类型. 例如, 如果像下面这样给一个属性(property)添加刚建立的自定义特性, 编译器就会抛出异常, 提示”SampleAttribute对本声明类型无效,只对声明类和方法有效

[SampleAttribute ("description for sample attribute", Author = "Test property")]
public string SomeProerty
{
    
get {return "ok"}
}

2.        使用定义好的自定义特性

[Sample ("description for sample attribute", Author = "Tester")]
public class TestApp
{
public void Test ()
{
        Console.WriteLine (
"Author {0}, Descr {1}", author, descr);
}

}

 
Sample(…)SampleAttribute(…)的省略写法. 该代码会命名编译器调用自定义特性对象的构造函数, 并传入字符串的值(“description for sample attribute”由构造函数初始化), 然后再将”Author”属性设置为”Tester”(Author = “Tester”是由属性赋值)来完成一个特性对象的创建. 当然还可以设置其他的属性的值, 例如:
[Sample (“description for sample attribute”, Author = “Tester”, Title = “Title for this”, Descr = “cover with old descr” )]
 
3.        利用反射检索特性信息
public static void Main(string[] args)
{
        MemberInfo info 
= typeof(TestApp); //TestApp是Test()所在的类名
        SampleAttribute sample = (SampleAttribute)Attribute.GetCustomAttribute(info, typeof(SampleAttribute));
        
if(sample != null)
{
    Console.WriteLine(
"Author: {0}, Descr: {1} ", sample.Author, sample.Descr);    
    Console.ReadLine();
}

}

 完整代码下载

posted on 2008-04-14 17:11  Niyo Wong  阅读(670)  评论(0编辑  收藏  举报