Jie

心若无尘,一花一世界,一鸟一天堂;心若静,已如涅磐,风声物语,皆可成言.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一个自定义属性(Attribute)的Demo

Posted on 2008-05-06 12:47  JieNet  阅读(284)  评论(0)    收藏  举报
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;//使用反射

namespace CUI.UseAttribute
{
    
//应用AttributeUsage特性来控制如何该特性的用处
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    
public class MyAttribute : Attribute//必须继承自Attribute类
    {
        
private string _userName;          //用户名
        private string _lastLoginTime;    //最后一次登录时间
        private string _remark;          //备注

        
private MyAttribute() { }

        
public MyAttribute(string userName,string lastLoginTime)
        
{
            
this._userName = userName;
            
this._lastLoginTime = lastLoginTime;
        }


        
public string UserName
        
{
            
get return _userName == null ? "UserName is Null" : this._userName; }
        }

        
public string LastLoginTime
        
{
            
get return _lastLoginTime; }
        }

        
public string Remark
        
{
            
get return _remark == null ? "Remark is Null" : _remark; }
            
set { _remark = value; }
        }


        
public override string ToString()
        
{
            
return String.Format("UserName:{1}{0}LastLoginTime:{2}{0}Remark:{3}{0}{0}",
                Environment.NewLine, 
this.UserName, this.LastLoginTime, this.Remark);
        }



    }


    [My(
"Jie""2008-05-06", Remark = "Hello,I'm Jie.")]
    
public class UseMyAttribute
    
{
        
public void SaySomething()
        
{
            Console.WriteLine(
"Say Something");
        }

    }


    
public class Test
    
{
        
public static void Main()
        
{
            Type type 
= typeof(UseMyAttribute);
            MyAttribute myAttribute 
= Attribute.GetCustomAttribute(type, typeof(MyAttribute)) as MyAttribute;

            
if (myAttribute != null)
            
{
                Console.WriteLine(
"UserName:{0}", myAttribute.UserName);
                Console.WriteLine(
"LastLoginTime:{0}", myAttribute.LastLoginTime);
                Console.WriteLine(
"Remark:{0}", myAttribute.Remark);
                Console.WriteLine();
            }


            
object obj = Activator.CreateInstance(typeof(UseMyAttribute));
            MethodInfo mi 
= type.GetMethod("SaySomething");
            mi.Invoke(obj, 
null);


            Console.ReadKey(
true);
        }

    }

}