开发者

C# explicit casting of derived types

If I create class A, and class B inherits from class A, why does C# require me to explicitly cast between them?

For example:

public class Mammal
{
}

public class Dog : Mammal
{
}

...

Mammal foo = new Dog(); // Invalid, wants an explicit cast
Mammal bar = (Mammal)new Dog();开发者_Python百科 // This one works

I'm just curious what the reasoning is behind that restriction.


Not quite sure what you mean? Both statements you have written compile and work fine.

Did you mean to write this as your question...?

Dog foo = new Mammal(); // Invalid, wants an explicit cast
Dog bar = (Dog)new Mammal(); // This one works

If that was what you mean (which would match the comments) then the first one will not compile because a Mammal is not a Dog and the compiler knows it, so it won't let you assign it (a Dog is a Mammal because it is derived from it, but the converse does not hold true). In the second one you're overriding the compiler's better judgement, and telling it you know better that a Mammal really is a Dog, but as it isn't, this statement will fail at runtime with an InvalidCastException.


They both work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜