-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathReflection.cs
More file actions
95 lines (82 loc) · 2.71 KB
/
Reflection.cs
File metadata and controls
95 lines (82 loc) · 2.71 KB
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
94
95
using System;
using System.Reflection;
namespace Samples
{
public class Reflection
{
public static void Main()
{
string typename = "Samples.Greetings";
string methodname = "SayGreetings";
string[] methargs = new string[1];
methargs[0] = "Bob";
Reflection reflection = new Reflection();
reflection.TestInvoke(typename,methodname,methargs);
}
public void TestInvoke(string typename,string methodname,string[] methodargs)
{
Assembly assembly;
Type type;
Object instance;
try
{
//get the requested type from current assembly
assembly = this.GetType().Assembly;
type = assembly.GetType(typename, true);
instance = Activator.CreateInstance(type);
}
catch(TypeLoadException)
{
Console.WriteLine("Could not load Type: {0}", typename);
return;
}
MethodInfo method = type.GetMethod(methodname);
if(method == null)
{
Console.WriteLine("Suitable method not found!");
return;
}
// Wrong number of parameters?
ParameterInfo[] param = method.GetParameters();
if(param.Length != methodargs.Length)
{
Console.WriteLine(method.DeclaringType + "." + method.Name + ": Method Signatures Don't Match!");
return;
}
// Ok, can we convert the strings to the right types?
Object[] newArgs = new Object[methodargs.Length];
for(int index = 0; index < methodargs.Length;index++)
{
try
{
newArgs[index] = Convert.ChangeType(methodargs[index], param[index].ParameterType);
}
catch(Exception e)
{
Console.WriteLine(method.DeclaringType + "." + method.Name + ": Argument Conversion Failed", e);
return;
}
}
if(!method.IsStatic)
method.Invoke(instance,methodargs);
else
Console.WriteLine("Suitable method not found!");
}
}
class Greetings
{
public void SayGreetings(string name)
{
SayHello(name);
SayGoodbye(name);
}
public void SayHello(string name)
{
Console.WriteLine( "Hello {0}!", name );
}
public void SayGoodbye(string name)
{
Console.WriteLine( "Goodbye {0}!", name );
}
}
}