-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
93 lines (78 loc) · 2.04 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Reflection;
using System.Linq;
namespace reflectionProj
{
public class Program
{
public static void Main()
{
Type personType = typeof(Person);
var properties = personType.GetProperties();
foreach (var item in properties)
{
Console.WriteLine($"Property: Type: {item.PropertyType.Name} | Name: {item.Name}");
}
Person person = new Person();
var methods = personType.GetMethods();
foreach (var item in methods)
{
Console.WriteLine($"Method: Type: {item.ReturnType.Name} | Name {item.Name}");
if (item.Name == "Print")
{
item.Invoke(person, null);
}
}
Console.WriteLine("-------------------------------");
AttributeTest(typeof(Person));
Console.ReadKey();
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public int ZipCode { get; set; }
[RunMethod(Count = 3)]
public void Print()
{
Console.WriteLine($"{FirstName} {LastName}");
}
[RunMethod(Count = 3)]
public void TestMethod()
{
Console.WriteLine("Hello from TestMethod");
}
public void Move(int newZipCode)
{
ZipCode = newZipCode;
Console.WriteLine($"{FirstName} {LastName} has been moved to {newZipCode}");
}
[RunMethod(Count = 1)]
public void SayHi()
{
Console.WriteLine($"Hi {FirstName}");
}
}
static void AttributeTest(Type type)
{
// Get the methods
var allMethods = type.GetMethods();
var methodsWithAttribute = allMethods.Where(m => m.GetCustomAttribute(typeof(RunMethodAttribute)) != null);
var obj = Activator.CreateInstance(type);
foreach (var item in methodsWithAttribute)
{
var attribute = (RunMethodAttribute)item.GetCustomAttribute(typeof(RunMethodAttribute));
Console.WriteLine($"{item.Name} run for {attribute.Count} times");
for (int i = 0; i < attribute.Count; i++)
{
item.Invoke(obj, null);
}
}
}
public class RunMethodAttribute : Attribute
{
public int Count { get; set; }
}
}
}