当错误发生时,我正在尝试从书中获取以下代码。我正在说它是因为错误使用as关键字而生成的。请帮我解决这个错误。此代码是子类化的示例。此代码生成两个错误(cs0266)。错误生成行位于Main方法中,并在行上方标记注释。
class Program
{
static void Main(string[] args)
{
// CS0266: Cannot implicitly convert type 'Dog' to 'Rottweiler
Rottweiler butch = new Rottweiler("Butch") as Dog;
// CS0266: Cannot implicitly convert type 'Dog' to 'Spaniel
Spaniel mac = new Spaniel("Mac", "yips") as Dog;
butch.Bark();
mac.Bark();
butch.DoYourThing();
mac.DoYourThing();
}
}
class Dog
{
protected string _name;
protected string _sound;
public Dog(string name)
{
_name = name; _sound = "barks";
}
public Dog(string name, string sound)
{
_name = name;
_sound = sound;
}
public void Bark()
{
Console.WriteLine("{0} {1} at you", _name, _sound);
}
public virtual void DoYourThing()
{
}
}
class Rottweiler : Dog
{
public Rottweiler(string name) : base(name) { }
public Rottweiler(string name, string sound) : base(name, sound) { }
public override void DoYourThing()
{
Console.WriteLine("{0} snarls at you, in a very menacing fashion!", _name);
}
}
class Spaniel : Dog
{
public Spaniel(string name) : base(name) { }
public Spaniel(string name, string sound) : base(name, sound) { }
public override void DoYourThing()
{
Console.WriteLine("{0} drools all over you, then licks you into submission!", _name);
}
}
答案 0 :(得分:2)
虽然你可以将Spaniel
投射到Dog
,但你不能反过来这样做。所以这段代码:
Spaniel mac = new Spaniel("Mac", "yips") as Dog;
转换为Dog
,然后尝试将其存储在Spaniel
变量中。但是你可以这样做:
Dog mac = new Spaniel("Mac", "yips") as Dog;
同样如@leppie所述,不需要as Dog
强制转换,因为存在从派生类到其基础的隐式强制转换:
Dog mac = new Spaniel("Mac", "yips");
答案 1 :(得分:1)
好吧,在这里:Rottweiler butch = new Rottweiler("Butch") as Dog;
您正在创建Rottweiler
的实例并将其投放到Dog
。
现在还可以,但是你要将Dog
的实例分配给Rottweiler
类型的变量 - 但这是不可能的。
由于Rottweiler
是从Dog
继承的,因此每Rottweiler
都是Dog
,但不是每Dog
都是Rottweiler
- 因此这隐式演员在任职期间无法完成。
所以要么删除强制转换为Dog
Rottweiler butch = new Rottweiler("Butch");
或将butch
的类型更改为Dog
:
Dog butch = new Rottweiler("Butch");
请注意,在这种情况下,您也不需要显式转换... as Dog
,它将通过赋值隐式完成;