方法 : 自動実装するプロパティを使用して簡易クラスを実装する (C# プログラミング ガイド)

この例では、一連の自動実装プロパティのカプセル化のみを行う、変更できない簡易クラスを作成する方法を示します。 参照型のセマンティクスを使用する必要がある場合は、構造体の代わりにこのような構造を使用します。

自動実装するプロパティには、get アクセサーと set アクセサーの両方が必要です。 クラスを変更不可にするには、set アクセサーを プライベート アクセサーとして宣言します。 ただし、プライベート set アクセサーを宣言した場合は、オブジェクト初期化子を使用してプロパティを初期化することができません。 コンストラクターまたはファクトリ メソッドを使用する必要があります。

使用例

次の例は、自動実装プロパティを持つ変更不可のクラスを実装する方法を 2 つ示しています。 最初のクラスではコンストラクターを使用してプロパティを初期化し、2 番目のクラスでは静的ファクトリ メソッドを使用します。


    // 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# プログラミング ガイド)