The error "there is an explicit conversion (you skip the cast)" occurs when creating an object:

I am interested in learning OOP concepts. When trying a simple program using Inheritance. I noticed this error. I can not understand why this error occurs? I gave this simple C # code below:

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

Someone will tell me what is really going on there ...

+4
source share
4 answers

You must understand the concept of Every Dog - Animal, but not all Animals - Dogs.

Program- a terrible name, let's get rid of it and make it Pomeranian: now everything will be clear.

Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian.

but you can do the following

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

Hope this helps.

+9
source

. .

+2

- , . , - . , , . .NET Framework , .

, , Dog Pomeranian. .

Dog dog = new Pomeranian();
Pomeranian pomeranian = (Pomeranian)dog; //explicit cast. This works. Would throw an InvalidCastException if the dog isn't a Pomeranian

, , , . - GetType() typeof().

Dog dog = new Pomeranian();

if(dog.GetType() == typeof(Pomeranian))
{
    Pomeranian p = (Pomeranian)dog; //explicit cast won't throw exception because we verified what we're doing is valid.
}

as.

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.

+2

Program Dog Program Dog.

a Program Dog, .

+1

Source: https://habr.com/ru/post/1534825/


All Articles