定義 Employee Class
namespace DeconstructDemo
{
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string PhoneNumber { get; set; }
public Employee(string name, int age, string phoenNumber)
{
Name = name;
Age = age;
PhoneNumber = phoenNumber;
}
// 參數必須宣告為 out
public void Deconstruct(out string name, out int age, out string phoneNumber)
{
name = Name;
age = Age;
phoneNumber = PhoneNumber;
}
// Deconstruct 可以多載
public void Deconstruct(out string name, out int age)
{
name = Name;
age = Age;
}
}
}
實際使用
namespace DeconstructDemo
{
internal class Program
{
static void Main(string[] args)
{
// Case1:一般寫法
var result = new Employee("姓名 1", 18, "111111111");
Console.WriteLine($"Case1:Name:{result.Name} - Age:{result.Age}");
// Case2:Deconstruct()
var (name2, age2, phoneNumber2) = new Employee("姓名 2", 28, "222222222");
Console.WriteLine($"Case2:Name:{name2}");
// Case3:Deconstruct() 多載
var (name3, age3) = new Employee("姓名 3", 38, "333333333");
Console.WriteLine($"Case3:Age:{age3}");
// Case4:不使用 var,明確指定型別
(string name4, int age4, string phoneNumber4) = new Employee("姓名 4", 48, "444444444");
Console.WriteLine($"Case4:PhoneNumber:{phoneNumber4}");
}
}
}
沒有留言:
張貼留言