如何使用接口实例化基类对象



我想实例化 Dog 类型的新对象。Dog 类实现接口 IAnimal。动物可以制造小动物,而该小动物可以成长为狗型的大动物。

public interface IAnimal
{ 
BabyAnimal baby();
int NumberOfLegs { get; set; }
}
public class Dog:IAnimal
{
    public Dog() 
{
}
    public int NumberOfLegs { get; set; }
    public BabyAnimal baby()
    {
    }
}
public class BabyAnimal
{
    public IAnimal WillGrowToBe(BabyAnimal baby)
    {
        //here I want to instantiate new Dog object
    }
}

如果您以通用方式引入婴儿和成年动物的概念,则可以更有力地对此进行建模:

public interface IAnimal
{
    int NumberOfLegs { get;}
}
public interface IBabyAnimal<TGrownAnimal>
    : IAnimal
    where TGrownAnimal : IGrownAnimal
{
    TGrownAnimal WillGrowToBe();
}
public interface IGrownAnimal : IAnimal
{
}
public class Catepillar : IBabyAnimal<Butterfly>
{
    public int NumberOfLegs { get;} = 100;
    public Butterfly WillGrowToBe() => new Butterfly();
}
public class Butterfly : IGrownAnimal
{
    public int NumberOfLegs { get; } = 0;
}

你可以与每只动物互动,作为腿数等简单IAnimal,很好,你可以写这样的东西:

public static class Extensions
{
    public static TGrown GrowUp<TGrown>(this IBabyAnimal<TGrown> baby)
        where TGrown : IGrownAnimal
    => baby.WillGrowToBe();
}

然后,您可以将其用于对付任何小动物以获得长大的形式。

如果你想区分小动物(例如 Pup ( 和成人 ( Dog ( 可以实现3接口:

// Animal in the most general: all we can do is to count its legs
public interface IAnimal { 
    // get: I doubt if we should maim animals; let number of legs be immutable
    int NumberOfLegs { get; } 
}
// Baby animal is animal and it can grow into adult one
public interface IBabyAnimal : IAnimal { 
    IAdultAnimal WillGrowToBe()
}
// Adult animal can give birth baby animal
public interface IAdultAnimal : IAnimal { 
    IBabyAnimal Baby();
}
// Dog is adult animal, it can birth pups
public class Dog : IAdultAnimal {
    public Dog() 
    public int NumberOfLegs { get; } => 4;
    public Baby() => new Pup();
}
// Pup is baby animal which will be dog when grow up
public class Pup : IBabyAnimal {
    public Pup() 
    public int NumberOfLegs { get; } => 4;
    public WillGrowToBe() => new Dog();
}

最新更新