對象初始化器

語法

類名 對象名 = new 類名(){屬性1 = 值1, 屬性2 = 值2, ......};

舉例


using System;

namespace LearnClass {
    class Program {
        static void Main (string[] args) {
            Person p = new Person(){ Age = 10, Name = "張三" };
            Console.WriteLine(p);
         }
    }
    class Person {
        public int Age { get; set; }
        public string Name{ get; set; }
        public override string ToString()
        {
            return Name + "今年" + Age + "歲!";
        }
    }
}

輸出結果

原文地址:https://www.cnblogs.com/ltozvxe/p/13975290.html