代码
using System;
using System.Reflection;
namespace HelloWorldApplication
{
class MyAttribute: System.Attribute{
public int a = 5;
}
[My()]
class A{
public void fun(){
Console.WriteLine("A fun");
}
}
class B{
[My()]
public void fun(){
Console.WriteLine("B fun");
}
}
class HelloWorld
{
static void Main(string[] args)
{
/* 我的第一个 C# 程序*/
Console.WriteLine("Hello World");
A a = new A();
a.fun();
Type type = typeof(A);
foreach (Object attributes in type.GetCustomAttributes(false))
{
MyAttribute dbi = (MyAttribute)attributes;
Console.WriteLine(dbi.a);
}
Type bType = typeof(B);
foreach (MethodInfo m in type.GetMethods()){
foreach (Attribute b in m.GetCustomAttributes(true)){
MyAttribute dbi = (MyAttribute)b;
Console.WriteLine(dbi.a);
}
}
Console.ReadKey();
}
}
}