속성(property)------------------------------------------------------------------------------------------------------------------------


객체지향프로그래밍에서 일반적으로 맴버에 접근하기 위한 방법으로 Get함수와 Set함수를 만드는 것이 일반적이다.

하지만 C#에서는 이를 좀더 간편하게 하기 위해서 프로퍼티라고 부르는 문법을 지원한다.


namespace ConsoleApplication1

{

    class home

    {

        int age; -> C#에서도 C++과 같이 다른 지정이 없으면 private로 선언된다.


        public int Age -> age와는 다른 Age를 property로 선언했다.

        {

            get

            {

                return age; -> 값을 가져오는 속성을 저장한다.

            }

            set

            {

                age = value; -> 값을 대입하는 속성을 저장한다.

            }

        }

    }


    class Program

    {

        static void Main()

        {

            home home1 = new home();

            home1.Age = 5; -> 자동으로 Age중 set을 호출한다.

            Console.WriteLine(home1.Age); -> 자동으로 Age중 get을 호출한다.

            int a;

            a = home1.Age; -> 자동으로 Age중 get을 호출한다.

            Console.WriteLine(a);

        }

    }

}


참 편하다. 일일이 함수를 호출할 필요가 없이 자연적으로 연산자 오버로딩을 한것처럼 사용할 수가 있다.


하지만 속성은 더욱더 간략화된 방식으로 이용이 가능하다 다음을 보자.


namespace ConsoleApplication1

{

    class Contact

    {

        // Read-only properties.

        public string Name { get; private set; } -> get은 선언을 하나로 묶는다. set은 private성향으로 아무나 접근하지 못하도록 막는다.

        public string Address { get; private set; } -> get은 선언을 하나로 묶는다. set은 private성향으로 아무나 접근하지 못하도록 막는다.


        // Public constructor.

        public Contact(string contactName, string contactAddress) -> 생성자 그런데 public

        {

            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; } -> get은 선언을 하나로 묶는다. set은 private성향으로 아무나 접근하지 못하도록 막는다.

        public string Address { get; private set; } -> get은 선언을 하나로 묶는다. set은 private성향으로 아무나 접근하지 못하도록 막는다.


        // Private constructor.

        private Contact2(string contactName, string contactAddress) -> 생성자 그런데 private

        {

            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[4 - i], addresses[4 - i]);


            Console.WriteLine();


            // Console output is identical to query1.

            var list2 = query2.ToList();


            foreach (var contact in list2)

            {

                Console.WriteLine("{0}, {1}", contact.Name, contact.Address); 

-> 값을 가져오는 것은 아무런 이상이 없다. 즉 get은 이상없이 작동한다. 애초에 public였으니 하지만

                contact.Name = 0; 이런 구문을 쓰면 당근 막힌다.


            }


            // List elements cannot be modified by client code.

            // CS0272:

            // list2[0].Name = "Eugene Zabokritski"; 


            // Keep the console open in debug mode.

            Console.WriteLine();

            Console.WriteLine("Press any key to exit.");

            Console.ReadKey();

        }

    }


}

Posted by JJOREG