我正在阅读这篇文章,以删除C#中的开关案例,并使用多态性来实现它。Polymorphim:如何创建接口的动态实例
https://refactoring.guru/replace-conditional-with-polymorphism
这里是我的代码,但:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Consolas
{
public class Program
{
static void Main(string[] args)
{
var animalType = "Dog"; //consider this as an argument supplied to the app
//How to create dynamic instance for IAnimal ???
//Is Activator.CreateInstance the only way to achieve it ??
//IAnimal animal = ..what here ?
//animal.Bark();
}
}
public interface IAnimal
{
void Bark();
}
public class Dog: IAnimal
{
public void Bark()
{
Console.WriteLine("Bow Bow");
}
}
public class Cat: IAnimal
{
public void Bark()
{
Console.WriteLine("Meow Meow");
}
}
}
我如何为接口创建实例,以便它可以动态调用该方法的树皮。
有人可以提供最好的方式,不只是一个工作。
结帐[依赖注入设计模式(https://msdn.microsoft.com/en-us/library/hh323705(V = VS.100 ).aspx) – Sid