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

时间:2019-06-05 11:01:44

标签: c# .net interface

我想实例化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
    }

}

2 个答案:

答案 0 :(得分:0)

如果要区分小动物(例如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();
}

答案 1 :(得分:0)

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

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

然后您可以对任何任何小动物使用这种动物来获得成长的动物形态。