举例解释的话可能会有一点好,但是,不知道是否贴切:一个Class或者是Function在创作后需要知道编写它的作者的一些信息,比如名字,年龄,擅长,或者联系电话什么的,但是,这些东西无法在Class里面写入,因此,可以用特性来帮忙.
我们将作者的所有信息写入到一个Class里面(一般情况下建议用属性(Property)和构造函数来输入一些信息),然后将其标注为特性类:
class MyAttributes : Attributes
{}
然后将其标注在需要使用的元素上面,我们这里暂时描述Class:
[MyAttributes()]
public class A
{}
这样,一个特性的创建和使用便完成了.
如何让代码知道我们的特性存在呢?关键就需要创建一个搜索特性的Class,这个类的目的是查找指定的类,看它是否具备了指定的特性,如果是,则完成相关操作,如果不是,就报错误或者执行其它的操作(甚至不做任何操作).
因此,使用特性的步骤总共为四个步骤:
1.创建一个特性类;
2.将特性类和相关的元素联系起来;
3.创建一个搜索类.
4.利用搜索类进行搜索后执行相关的操作.
以下是个人实验的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
class Program
{
static void Main(string[] args)
{
Type t = typeof(Show); //将Show类的类型作为参数进行传递
AuthorAttributesCheck aa = new AuthorAttributesCheck(t); //通过AuthorAttributesCheck类来搜索看Show类是否存在特性类
if (aa != null) //如果存在的话,就进行数据的读出
{
Console.WriteLine("The Author is {0} and {1}", aa.GetName(),aa.GetNotes ());
}
Console.ReadLine();
}
}
public class Author:Attribute //这个就是指明从Attribute继承出来的自定义特性
{
protected string _name;
protected string _notes;
public Author (string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
public string Notes
{
get
{
return _notes;
}
set
{
_notes = value;
}
}
}
[Author("shaw")] //在这里标注出特性,将它和Show类联系,即可得到Show类作者的信息
public class Show
{
public Show ()
{
Console.WriteLine("YES");
}
}
public class AuthorAttributesCheck
{
protected Type _type; //创建一个Type实例用来获得参数类型
public AuthorAttributesCheck(Type type)
{
_type = type;
}
public string GetName()
{
foreach (Attribute attrib in _type.GetCustomAttributes(true)) //获得一个自定义特性数组
{
Author author = attrib as Author; //将特性实例和自定义特性数组做比较,看是否存在相同的数组
if (attrib != null)
{
return author.Name; //如果存在的话,即说明type参数的类是被Author特性标注,因此,获取信息
}
}
return null;
}
public string GetNotes() //获取Notes信息的方法
{
foreach (Attribute attrib in _type.GetCustomAttributes(true))
{
Author notes = attrib as Author;
if(notes != null)
{
notes.Notes = "No.1";
return notes.Notes;
}
}
return null;
}
}