.NET反射的简单示例
时间:2011-03-21 来源:蓝鸿鹄
1: (1)namespace ClassLibrarySport
2: {
3: public abstract class Sport
4: {
5: protected string name;
6: public abstract string GetName();
7: public abstract string GetDuration();
8: }
9: }
= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =
1: (2)namespace ClassLibrarySomeSports//该项目添加了对(1)的引用
2: {
3: public class Football : ClassLibrarySport.Sport
4: {
5: public Football()
6: {
7: name = "Football";
8: }
9: public override string GetName()
10: {
11: return name;
12: }
13: public override string GetDuration()
14: {
15: return "four 15 minute quarters";
16: }
17: }
18: }
= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =
1: (3)namespace ConsoleAssemblyTest//该项目添加了对(1)的引用
2: {
3: class Program
4: {
5: static void Main(string[] args)
6: {
7: Assembly assembly = Assembly.LoadFrom(@"E:\ClassLibrarySomeSports\
8: bin\Debug\ClassLibrarySomeSports.dll");
9: Type[] types = assembly.GetTypes();
10:
11: Console.WriteLine("Get Type From ClassLibrarySomeSports.dll:");
12: for (int i = 0; i < types.Length; i++)
13: {
14: Console.WriteLine(types[i].Name);
15: }
16:
17: //使用GetConstructor()方法获取对应类型的构造器,从而构造出该类型的对象
18: Console.WriteLine("Use Method GetConstructor():");
19: ConstructorInfo ci = types[0].GetConstructor(new Type[0]);
20: ClassLibrarySport.Sport sport = (ClassLibrarySport.Sport)ci.Invoke(new object[0]);
21: Console.WriteLine(sport.GetName() + " has " + sport.GetDuration());
22:
23: //使用Activator.CreateInstance()方法构造出该类型的对象
24: //使用assembly.CreateInstance()返回为null,??
25: Console.WriteLine("Use Method CreateInstance():");
26: ClassLibrarySport.Sport sport1 = (ClassLibrarySport.Sport)
27: Activator.CreateInstance(types[0]);
28: Console.WriteLine(sport1.GetName() + " has " + sport1.GetDuration());
29:
30: //反射指定类型中的名称为“GetDuration”的方法,通过Invoke()方法执行该方法
31: object objSport = Activator.CreateInstance(types[0]);
32: MethodInfo method = types[0].GetMethod("GetDuration");
33: object o = method.Invoke(objSport, new object[0]);
34: Console.WriteLine(o as string);
35:
36: Console.Read();
37: }
38: }
39: }
= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =
Output:
Get Type From ClassLibrarySomeSports.dll:
Football
Use Method GetConstructor():
Football has four 15 minute quarters
Use Method CreateInstance():
Football has four 15 minute quarters
four 15 minute quarters
Output:
Get Type From ClassLibrarySomeSports.dll:
Football
Use Method GetConstructor():
Football has four 15 minute quarters
Use Method CreateInstance():
Football has four 15 minute quarters
four 15 minute quarters
相关阅读 更多 +