C# “错误”;存在显式转换(是否缺少转换)“;在创建对象时发生:

C# “错误”;存在显式转换(是否缺少转换)“;在创建对象时发生:,c#,asp.net,inheritance,C#,Asp.net,Inheritance,我对学习OOPs概念感兴趣。在尝试使用继承的简单程序时。我注意到了这个错误。我不明白为什么会发生这种错误?我在下面给出了简单的c代码: class Animal { public void Body() { Console.WriteLine("Animal"); } } class Dog : Animal { public void Activity() { Console.WriteLine("Dog Activity

我对学习OOPs概念感兴趣。在尝试使用继承的简单程序时。我注意到了这个错误。我不明白为什么会发生这种错误?我在下面给出了简单的c代码:

class Animal
{
    public void Body()
    {
        Console.WriteLine("Animal");
    }
}
class Dog : Animal
{
    public void Activity()
    {
        Console.WriteLine("Dog Activity");
    }
}

class Pomeranian : Dog
{
    static void Main(string[] args)
    {
        //Dog D = new Dog();
        Dog D = new Pomeranian();    -----> No error occur at this line
        Pomeranian P = new Dog();    -----> Error occur at this line
        D.Body();
        D.Activity();
        Console.ReadLine();
    }             
}

任何人请告诉我那里到底发生了什么…

你不能从
狗那里得到
程序
,因为
程序
子类


但是对于多态性,一个
程序
就是一只
,而不是反过来。

你必须理解每个狗都是动物的概念,但不是所有的动物都是狗

Program
是一个可怕的名字,让我们摆脱它,让它成为
Pomeranian
:现在一切都清楚了

Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian.
但是你可以做以下事情

Dog d = new Pomeranian();//You know why this works :)

我希望这会有所帮助。

您不能从类型child创建parent的实例。这违反了遗传的概念。

波美拉尼亚人是狗,但狗不一定是波美拉尼亚人。这在现实生活中是正确的,当您的面向对象类正确地相互继承时也是如此。在现实生活中,你对一只狗进行DNA测试,以确认它是一只博美犬。在.NET框架中,我们有一些函数和操作符可以帮助我们实现这一点

假设您确实知道您的
实例实际上是一只
波美拉尼亚狗
。您可以执行显式强制转换

Dog dog = new Pomeranian();
Pomeranian pomeranian = (Pomeranian)dog; //explicit cast. This works. Would throw an InvalidCastException if the dog isn't a Pomeranian
您希望确定实例实际上是您要强制转换到的类型,以避免异常。一种方法是利用和

另一种方法是使用操作符

Dog dog = new Pomeranian();
Pomeranian pomeranian = dog as Pomeranian; //If the dog isn't actually a Pomeranian, the pomeranian would be null.
使用as运算符基本上等同于此

Dog dog = new Pomeranian();
Pomeranian pomeranian = null;

if(dog.GetType() == typeof(Pomeranian))
{
    pomeranian = (Pomeranian)dog;
}
显然,当您的所有代码都是同一个块时,很容易通过观察来判断底层类型。但是当您开始使用泛型集合和其他类似的东西,并在类之间传递它们时,有时您不知道类型是什么,此时在强制转换之前检查类型变得很重要


见MSDN。

波美拉尼亚人是狗,但波美拉尼亚人不一定是狗
我想你的意思是
,但狗不一定是波美拉尼亚人
@ChrisDunaway抓得好!
Dog dog = new Pomeranian();
Pomeranian pomeranian = null;

if(dog.GetType() == typeof(Pomeranian))
{
    pomeranian = (Pomeranian)dog;
}