码迷,mamicode.com
首页 > 其他好文 > 详细

动物点名(用反射)

时间:2015-05-29 22:57:36      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

 

//主程序

class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请录入动物名称");
string str = Console.ReadLine().ToLower();
Assembly ass = Assembly.Load("动物点名(反射)");
Type[] type = ass.GetTypes();
foreach (Type t in type)
{
if (str==t.Name.ToLower())
{
MethodInfo m = t.GetMethod("Shout");
object obj = Activator.CreateInstance(t);
PropertyInfo[] pop = t.GetProperties();
m.Invoke(obj, null);
break;
}
}
}
}
}

//类

public abstract class Animal    //父类
{
public string Name { get; set; }
public int Age { get; set; }

public abstract void Shout();
}
public class Cat : Animal   //子类,继承父类
{
public Cat()
{
base.Name = "花花 ";
base.Age = 2;
}
public override void Shout()
{
Console.WriteLine("我是小猫{0},今年{1}岁,喵喵喵",base.Name,base.Age );
}
}
public class Dog : Animal    //子类,继承父类
{
public Dog()
{
base.Name = "阿黄";
base.Age = 4;
}
public override void Shout()
{
Console.WriteLine("我是小狗{0},今年{1}岁,汪汪汪",base.Name,base.Age );
}
}
public class Pig : Animal   //子类,继承父类
{
public Pig()
{
base.Name = "肥肥";
base.Age = 5;
}
public override void Shout()
{
Console.WriteLine("我是小猪{0},今年{1}岁",base.Name,base.Age );
}
}

动物点名(用反射)

标签:

原文地址:http://www.cnblogs.com/gsj2ronger918/p/4539528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!