自定义反射的示例

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Reflection;
 6 
 7 namespace attribute
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Tester t = new Tester();
14             t.CannotRun();
15 
16             Type tp = typeof(Tester);
17 
18             MethodInfo methodinfo = tp.GetMethod("CannotRun");
19             TestAttribute myatt = (TestAttribute)Attribute.GetCustomAttribute(methodinfo, typeof(TestAttribute));
20             myatt.RunTest();
21         }
22     }
23     class Tester
24     {
25         [Test("Error Here")]
26         public void CannotRun()
27         {
28             Console.WriteLine("fuck this is a error");
29         }
30     }
31     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
32     public class TestAttribute : System.Attribute
33     {
34         public TestAttribute(string name)
35         {
36             Console.WriteLine(name);
37         }
38         public void RunTest()
39         {
40             Console.WriteLine("test here");
41         }
42     }
43 }
44 
原文地址:https://www.cnblogs.com/kakaliush/p/1885982.html