1. 程式人生 > >C# 隱式轉換

C# 隱式轉換

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog dog1 = new Dog("jack");
            dog1.ShowName();
            
// 使用隱式轉換 Cat cat1 = dog1; cat1.ShowName(); // 使用顯式轉換 Dog dog2 = (Dog)cat1; dog2.ShowName(); } } public class Dog { private string Name; public Dog(string dname) { Name = dname; }
public void ShowName() { Console.WriteLine("這是一條狗:{0}", Name); } // 隱式轉換,將狗的類轉換為貓的類 public static implicit operator Cat(Dog dog) { return new Cat(dog.Name); } } public class Cat { private string Cname; public
Cat(string cname) { Cname = cname; } public void ShowName() { Console.WriteLine("這是一條貓:{0}", Cname); } // 顯式轉換 public static explicit operator Dog(Cat cat) { return new Dog(cat.Cname); } } }