spr*_*t12 6 c# polymorphism inheritance
我说过3个课程,动物,猫和狗.
// calling code
var x = new Animal("Rex"); // would like this to return a dog type
var x = new Animal("Mittens"); // would like this to return a cat type
if(x.GetType() == typeof(Dog))
{
x.Bark();
}
else
{
x.Meow();
}
class Animal
{
public Animal(string name)
{
// check against some list of dog names ... find rex
// return Animal of type Dog.
// if not...
// check against some list of cat names ... find mittens
// return Animal of type Cat.
}
}
Run Code Online (Sandbox Code Playgroud)
这有可能吗?如果没有,我可以做类似的事情吗?
您正在寻找的是"虚拟构造函数"(C#中不可能)或工厂模式.
class Animal
{
// Factory method
public static Animal Create(string name)
{
Animal animal = null;
... // some logic based on 'name'
animal = new Zebra();
return animal;
}
}
Run Code Online (Sandbox Code Playgroud)
Factory方法也可以放在另一个(Factory)类中.这样可以提供更好的去耦等
没有.基本上正确的解决方法是使用静态方法,它可以创建正确类型的实例:
var x = Animal.ForName("Rex");
var x = Animal.ForName("Mittens");
...
public abstract class Animal
{
public static Animal ForName(string name)
{
if (dogNames.Contains(name))
{
return new Dog(name);
}
else
{
return new Cat(name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者这可以是类型(或其他)中的实例方法AnimalFactory.这将是一种更具扩展性的方法 - 例如,工厂可以实现一个接口,并且可以注入需要创建实例的类中.这实际上取决于上下文 - 有时这种方法是过度的.
基本上,new Foo(...)调用总是创建一个完全 的实例Foo.声明返回类型为的静态方法Foo可以返回与任何兼容类型的引用Foo.