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());
}
}
}
错误讯息:
错误CS0266无法隐式转换类型' ConsoleApplication12.Foo'到' ConsoleApplication12.Bar'。存在显式转换(您是否缺少演员?)ConsoleApplication12 C:\ Users \ chliu \ Documents \ Visual Studio 2015 \ Projects \ ConsoleApplication12 \ ConsoleApplication12 \ Program.cs
似乎"创建派生类的变量以通过基类引用对象"不被允许。为什么呢?
答案 0 :(得分:2)
如果没有演员表,这不起作用:
Bar test = (Bar)new Foo();
其他方面正在发挥作用:
Foo test = new Bar();
这是因为Bar
可以包含Foo
没有的内容,如果您尝试在Bar
创建的Foo
对象上访问这些内容,则会导致意外行为Foo
。
为了更明确一点,你可以问自己一个问题,以便更好地理解:
Bar
是Foo
吗?如果是,那么从Bar
到Foo actuallyBar = new Bar();
Bar = (Bar)actuallyBar; //this will succeed because actuallyBar is actually a Bar
的广告投放将像以下示例一样工作:
Foo foo = new Bar();//didn't even had to use explicit cast, because the compiler knows that Bar is a Foo
另一种投射方式总是有效,因为每当你问酒吧是否是Foo时答案都是肯定的!
<div id="pagecontent" class="wrapper">
<!--CREATE NEW DIV ELEMENT-->
<div id="forappend"></div>
<!--WANT APPENDED ELEMENT TO APPEND HERE-->
<div class="btnholder">
<a id="continue" class="continue" href="javascript:;">get more</a>
</div>
<!-- WANT TO KEEP AT BOTTOM HERE-->