创建一个 derived class 的变量来引用 base class 的对象

create a variable of derived class to refer an object of base class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication12
{
    public class Foo
    {
        public virtual bool DoSomething() { return false; }
    }

    public class Bar : Foo
    {
        public override bool DoSomething() { return true; }
    }

    public class Test
    {
        public static void Main()
        {
            Bar test = new Foo();
            Console.WriteLine(test.DoSomething());
        }
    }
}

错误信息:

Error CS0266 Cannot implicitly convert type 'ConsoleApplication12.Foo' to 'ConsoleApplication12.Bar'. An explicit conversion exists (are you missing a cast?) ConsoleApplication12 C:\Users\chliu\Documents\Visual Studio 2015\Projects\ConsoleApplication12\ConsoleApplication12\Program.cs

好像"create a variable of derived class to refer an object by base class"是不允许的。为什么?

如果没有强制转换,这是行不通的:

Bar test = (Bar)new Foo();

其他方法也行得通:

Foo test = new Bar();

这是因为 Bar 可以拥有 Foo 没有的东西,如果您尝试在创建的 Bar 对象上访问这些东西,将会导致意外行为来自 Foo.

更明确一点,你可以问自己一个问题来更好地理解转换:

FooBar 吗?如果是,那么从 FooBar 的转换将像以下示例一样工作:

Foo actuallyBar = new Bar();

Bar = (Bar)actuallyBar; //this will succeed because actuallyBar is actually a Bar

另一种转换方式始终有效,因为每次您询问 Bar 是否为 Foo 时,答案都是肯定的!

Foo foo = new Bar();//didn't even had to use explicit cast, because the compiler knows that Bar is a Foo