自定义转换:static + explicit/implicit operator +返回值类型名
using System;
namespace ConsoleHide {
class Program {
static void Main(string[] args) {
Cat cat = new Cat("十六");
Dog dog = cat;
dog.PrintName();
Dog dog2 = new Dog("十五");
Cat cat2 =(Cat)dog2;
cat2.PrintName();
}
}
public class Dog {
public string dogName;
public Dog(string name) {
dogName = name;
}
//隐式转换
public static implicit operator Dog(Cat cat) {
return new Dog(cat.catName);
}
public void PrintName() {
Console.WriteLine(dogName);
}
}
public class Cat {
public string catName;
public Cat(string name){
catName = name;
}
//显式转换
public static explicit operator Cat(Dog dog) {
return new Cat(dog.dogName);
}
public void PrintName() {
Console.WriteLine(catName);
}
}
}