C# attribute用法
2019-12-25 本文已影响0人
李药师_hablee
贴代码
using System;
using System.Reflection;
namespace my_attribute
{
[AttributeUsage(AttributeTargets.Class
| AttributeTargets.Method,
AllowMultiple = true)]
public class HelpAttribute : System.Attribute
{
public readonly string url;
private string topic;
public string Topic
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url)
{
this.url = url;
}
}
[HelpAttribute("https://msvc/MyClassInfo", Topic = "Test"),
Help("https://my.com/about/class")]
class MyClass
{
[Help("http;//my.com/about/method")]
public void MyMethod()
{
return;
}
}
class Program
{
static void Main()
{
Type myType = typeof(MyClass);
object[] attributes = myType.GetCustomAttributes(false);
for (int i = 0; i < attributes.Length; i++)
PrintAttributeInfo(attributes[i]);
MemberInfo[] myMembers = myType.GetMembers();
for(int i=0;i<myMembers.Length;i++)
{
Console.WriteLine("\nNumber {0}: ", myMembers[i]);
object[] myAttributes = myMembers[i].GetCustomAttributes(false);
for (int j = 0; j < myAttributes.Length; j++)
PrintAttributeInfo(myAttributes[j]);
}
}
static void PrintAttributeInfo(object attr)
{
if(attr is HelpAttribute)
{
HelpAttribute attrh = (HelpAttribute)attr;
Console.WriteLine("------Url:" + attrh.url + " topic:" + attrh.Topic);
}
}
}
}