显示转换:static explicit operator
隐式转换:static implicit operator
internal class Program
{
static void Main(string[] args)
{
//基础转换
int a = 1; float b = a;
int c = 'c';//char类型可以隐式转换成对应的ASCII码
int d =Convert.ToInt32(null); //显示
Console.WriteLine($"{a},{b},{c},{d}");
//自定义转换
Dog dog = new Dog("阿黄");
dog.Speak();
Cat cat = (Cat)dog;//显示
cat.Speak();
dog = new Cat("咪咪");////隐式
dog.Speak();
Console.ReadKey();
}
}
abstract public class Animal
{
public string _name = "";
public Animal(string name)
{
this._name = name;
}
abstract public void Speak();
}
public class Dog : Animal
{
public Dog(string name) : base(name)
{
}
public override void Speak()
{
Console.WriteLine($"汪汪!我的名字叫{_name}");
}
//传入的参数是要转换的实例,而操作符类型是转换后的实例
public static implicit operator Dog(Cat cat)
{
return new Dog(cat._name);
}
}
public class Cat:Animal
{
public Cat(string name) : base(name)
{
}
public override void Speak()
{
Console.WriteLine($"喵喵!我的名字叫{_name}");
}
public static explicit operator Cat(Dog dog)
{
return new Cat(dog._name);
}
}
标签:转换,name,自定义,dog,Dog,Cat,public,Speak From: https://www.cnblogs.com/xixi-in-summer/p/17212562.html