共用方式為


HOW TO:使用自動實作的屬性來實作輕量型類別 (C# 程式設計手冊)

本範例顯示如何建立不變的、輕量型類別,該類別只提供封裝自動實作屬性集的服務。 使用這種建構而非必須使用參考型別語意時的結構 (Struct)。

請注意,使用自動實作屬性時,會同時需要 getset 這兩個存取子。 如果要將類別設定為不變的,請將 set 存取子宣告為 private。 不過,當您宣告私用 set 存取子時,不能夠使用物件初始設定式來初始化屬性。 必須使用建構函式或 Factory 方法。

範例

下列範例示範兩種方法,教您如何實作具有自動實作屬性的不可變類別。 第一個類別使用建構函式來初始化屬性,而第二個類別使用靜 Factory 方法。


    // This class is immutable. After an object is created,
    // it cannot be modified from outside the class. It uses a
    // constructor to initialize its properties.
    class Contact
    {
        // Read-only properties.
        public string Name { get; private set; }
        public string Address { get; private set; }

        // Public constructor.
        public Contact(string contactName, string contactAddress)
        {
            Name = contactName;
            Address = contactAddress;               
        }
    }

    // This class is immutable. After an object is created,
    // it cannot be modified from outside the class. It uses a
    // static method and private constructor to initialize its properties.   
    public class Contact2
    {
        // Read-only properties.
        public string Name { get; private set; }
        public string Address { get; private set; }

        // Private constructor.
        private Contact2(string contactName, string contactAddress)
        {
            Name = contactName;
            Address = contactAddress;               
        }

        // Public factory method.
        public static Contact2 CreateContact(string name, string address)
        {
            return new Contact2(name, address);
        }
    }

    public class Program
    { 
        static void Main()
        {
            // Some simple data sources.
            string[] names = {"Terry Adams","Fadi Fakhouri", "Hanying Feng", 
                              "Cesar Garcia", "Debra Garcia"};
            string[] addresses = {"123 Main St.", "345 Cypress Ave.", "678 1st Ave",
                                  "12 108th St.", "89 E. 42nd St."};

            // Simple query to demonstrate object creation in select clause.
            // Create Contact objects by using a constructor.
            var query1 = from i in Enumerable.Range(0, 5)
                        select new Contact(names[i], addresses[i]);

            // List elements cannot be modified by client code.
            var list = query1.ToList();
            foreach (var contact in list)
            {
                Console.WriteLine("{0}, {1}", contact.Name, contact.Address);
            }

            // Create Contact2 objects by using a static factory method.
            var query2 = from i in Enumerable.Range(0, 5)
                         select Contact2.CreateContact(names[i], addresses[i]);

            // Console output is identical to query1.
            var list2 = query2.ToList();

            // List elements cannot be modified by client code.
            // CS0272:
            // list2[0].Name = "Eugene Zabokritski"; 

            // Keep the console open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();                
        }
    }

/* Output:
    Terry Adams, 123 Main St.
    Fadi Fakhouri, 345 Cypress Ave.
    Hanying Feng, 678 1st Ave
    Cesar Garcia, 12 108th St.
    Debra Garcia, 89 E. 42nd St.
*/

編譯器會對每個自動實作屬性建立支援欄位。 這些欄位無法從來源程式碼直接存取。

請參閱

參考

屬性 (C# 程式設計手冊)

struct (C# 參考)

物件和集合初始設定式 (C# 程式設計手冊)