您的位置:首页 > 编程语言 > C#

C#的Attribute

2015-09-04 09:03 621 查看
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace codeTest
{
class Program
{
static void Main(string[] args)
{
//通过反射来获取Attribute中的信息
MyAttribute myattribute;
foreach (var attr in typeof(MyClass).GetCustomAttributes(true))
{
myattribute = attr as MyAttribute;
Console.WriteLine(myattribute.Name);
}

Console.ReadLine();
}
}

//自定义Attribute经常用到 AttributeUsage ,可以限制自定义Attribute的使用范围
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
class MyAttribute : Attribute
{
//MyAttribute必须继承Attribute
string name;

public MyAttribute(string nameIn)
{
this.name = nameIn;
}

public string Name
{
get
{
return this.name;
}
}

public string desc
{
get;
set;
}
}

//MyAttribute可以缩写为  My
[My("MyAttribute",desc="MyClass")]
class MyClass
{

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: