dog转换成cat之后,cat没有继承dog的名字(构造方法),名字变成了空
public static“ explicit” operator Cat(Dog dog)
改成隐士转换
输出:我叫hommy
wow
我叫
meow
using System;
namespace 装箱与拆箱
{ abstract public class pet
{
public string name;
public pet(string name)
{
Console.WriteLine("我叫" + name);
}
abstract public void speak();
}
public class Dog : pet
{
public Dog(string name):base(name)
{
}
public override void speak()
{
Console.WriteLine("wow");
}
public static explicit operator Cat(Dog dog)
{
return new Cat(dog.name);
}
}
public class Cat : pet
{
public Cat(string name) : base(name)
{
}
public override void speak()
{
Console.WriteLine("meow");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog("hommy");
dog.speak();
Cat cat = (Cat)dog;
cat.speak();
}
}
}