using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test01
{
//添加public,改为抽象类//publicabstractclass Animal
{
//抽象方法必须在抽象类中//publicabstractvoidShout();
}
}
添加Cat类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test01
{
//添加public,继承Animal//publicclass Cat : Animal
{
//选中Animal按ALT+SHIFT+F10可直接生成抽象方法的实现代码//publicoverridevoidShout()
{
Console.WriteLine("maomao...");
}
}
}
添加Dog类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test01
{
publicclass Dog : Animal
{
publicoverridevoidShout()
{
Console.WriteLine("wangwang...");
}
}
}
添加Pig类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test01
{
publicclass Pig : Animal
{
publicoverridevoidShout()
{
Console.WriteLine("hengheng...");
}
}
}
编写主程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespaceTest01
{classProgram
{staticvoid Main(string[] args)
{
Console.WriteLine("Input animal:");
string name = Console.ReadLine();
//先输入GetAnimalByName(name),然后按SHIFT+ALT+F10可直接生成实现方法//
Animal animal = GetAnimalByName(name);
if(animal!=null)
{
animal.Shout();
}
Console.ReadKey();
}
privatestatic Animal GetAnimalByName(string name)
{
Animal animal = null;
switch(name)
{
case"cat":
animal = new Cat();
break;
case"dog":
animal = new Dog();
break;
case"pig":
animal = new Pig();
break;
}
return animal;
}
}
}