动物点名(用反射)

 

//主程序

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 );
}
}

posted @ 2015-05-29 22:24  ronger918  阅读(153)  评论(0编辑  收藏  举报