C# attribute 是不同于属性的, 我们自己写的attribute 姑且叫UserAttribute 继承于attribute 他的作用是什么。他只是做个标记,对类 属性做个标记。一个类或属性 或方法 可以有多个标记。 标记的目的是为了给别人使用时候,识别。从而做成相应的动作。貌似也实现了多态。使用方法 :
1) 获得 Type --> GetType
2) 获得Mothods --->GetMethods()
3) 获得Attributes -->GetCustomAttributes()
4) is 判断
using System;
using System.Reflection;
#region ll
namespace QueryAttribs
{
public enum RemoteServers
{
JEANVALJEAN,
JAVERT,
COSETTE
}
public class RemoteObjectAttribute : Attribute
{
public RemoteObjectAttribute(RemoteServers Server)
{
this.server = Server;
}
protected RemoteServers server;
public string Server
{
get
{
return RemoteServers.GetName(
typeof(RemoteServers), this.server);
}
}
}
[RemoteObject(RemoteServers.COSETTE)]
class MyRemotableClass
{
}
class Test
{
//[STAThread]
//static void Main(string[] args)
//{
// Type type = typeof(MyRemotableClass);
// foreach (Attribute attr in
// type.GetCustomAttributes(true))
// {
// RemoteObjectAttribute remoteAttr =
// attr as RemoteObjectAttribute;
// if (null != remoteAttr)
// {
// Console.WriteLine(
// "Create this object on {0}.",
// remoteAttr.Server);
// }
// }
// Console.ReadLine();
//}
}
}
#endregion
namespace MethodAttribs
{
public class TransactionableAttribute : Attribute
{
public TransactionableAttribute()
{
}
}
class SomeClass
{
[Transactionable]
public void Foo()
{}
public void Bar()
{}
[Transactionable]
public void Goo()
{}
}
class Test
{
[STAThread]
static void Main(string[] args)
{
SomeClass ks = new SomeClass();
MethodInfo[] arr= ks.GetType().GetMethods();
foreach (MethodInfo method in arr)
foreach (Attribute attr in method.GetCustomAttributes(true))
{
if (attr is TransactionableAttribute)
{
Console.WriteLine(
"{0} is transactionable.",
method.Name);
}
}
Console.WriteLine("#########");
Type type = Type.GetType("MethodAttribs.SomeClass");
foreach (MethodInfo method in type.GetMethods())
{
foreach (Attribute attr in
method.GetCustomAttributes(true))
{
if (attr is TransactionableAttribute)
{
Console.WriteLine(
"{0} is transactionable.",
method.Name);
}
}
}
Console.ReadLine();
}
}
}