这篇小文章主要讲述如何用C#来实现自定义属性。那就先开始讲讲 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在C#中实现自定义属性");
            Console.ReadKey(
false);
        }
    }

相关文章: