新经济地理

空间信息技术与区域经济
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在C#中实现自定义属性

Posted on 2007-08-04 15:08  wuxb  阅读(1229)  评论(0编辑  收藏  举报
   这篇小文章主要讲述如何用C#来实现自定义属性。那就先开始讲讲有关Attributes的东西吧!
  
要在自己的类中实现Attributes,那么这个类得继承Attribute类。具体点就是得把AttributeUsageAttribute关键字放在自定义类的前面。AttributeUsageAttribute关键字描述了你的自定义属性能够应用在那些目标上。这些目标包括:module,element,class,constructor,delegate,enum,event,field,genericParameter,interface,method,其中All表示可以应用于所有的目标上。废话少说,看例子好了.
using System;
using System.Collections.Generic;
using System.Text;

namespace AttributesSample
{
    
/// <summary>
    
/// AttributeTargets.Class表示我们自定义的属性只能用于类上。
    
/// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    
public class MyCustomAttribute : Attribute
    {
        
private string attributevalue;

        
public MyCustomAttribute(string AttributeValue)
        {
            attributevalue 
= AttributeValue;
        }

        
public string AttributeValue
        {
            
get
            {
                
return attributevalue;
            }
        }
    }

    
/// <summary>
    
/// 为了使用我们自定义的属性,下面这个类是一个基类。其它的类要使用这个AttributeValue的话就得继承这个基类。
    
/// </summary>
    public class MyCustom
    {
        
public string AttributeValue
        {
            
get
            {
                
string              Value   = null;         
                Type                type    
= this.GetType();
                MyCustomAttribute[] attribs 
= (MyCustomAttribute[])type.GetCustomAttributes(typeof(MyCustomAttribute), true);

                
if (attribs.Length > 0)
                {
                    MyCustomAttribute attrib 
= attribs[0];
                    Value 
= attrib.AttributeValue;
                }
                
return Value;
            }
        }
    }
}
    
/// <summary>
    
/// 这个类用来测试我们自定义的属性,它继承了MyCustom才能通过Property来访问
    
/// </summary>
    [MyCustom("Test")]
    
class TestClass : MyCustom
    {
 
    }

    
class Program
    {
        
static void Main(string[] args)
        {
            TestClass test 
= new TestClass();
            Console.WriteLine(
"The value of the attribute is: " + test.AttributeValue);
            Console.WriteLine(
"Press any key");
            Console.ReadKey(
false);
        }
    }
这个例子来自:www.codeproject.com,这个网站很不错,很多东西可以学到.