본문 바로가기
IT Study/C#

[C#] 프로퍼티(Property), 익명 타입

by dev_huhu 2021. 1. 25.
반응형

1. 프로퍼티(Property)

자바에서 Getter Setter 를 사용할 때 클래스의 멤버 변수가 많아질 때마다 코드가 길어지는 불편함이 있었다.

C#에서의 프로퍼티라는 메서드(?)도 필드(?)도 아닌 이 기능으로 정리하자면 이렇다.

class Human
    {
        private string name;
        private int age;

        public string Name { get { return name; } set { name = value; } }
        public int Age { get { return age; } set { age = value; } }
    }

 

이를 조금 더 단순화 시켜서 이런 식으로 정의할 수 있다.

자동구현 프로퍼티 라고 한다.

 

using System;

namespace ConsoleApplication1
{
//-------------------------------------------------------------------
    class Human
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
//-------------------------------------------------------------------
    class ExClass
    {        
        static void Main(string[] args)
        {
            Human Lee = new Human();
            Lee.Name = "이순신";
            Lee.Age = 40;
            Console.WriteLine("이름: " + Lee.Name + ", 나이: " + Lee.Age);
        }
    }
}

 

2. 익명 타입

- 익명 타입을 사용하면 별도의 클래스 없이도 원하는 멤버를 가진 객체를 생성할 수 있다.

using System;

namespace ConsoleApplication1
{

    class ExClass
    {        
        static void Main(string[] args)
        {
            var Lee = new { Name = "이순신", Age = 32  };
            Console.WriteLine("이름: " + Lee.Name + ", 나이: " + Lee.Age);
        }
    }
}

반응형

'IT Study > C#' 카테고리의 다른 글

[C#] 리플렉션(Reflection), 애트리뷰트(Attribute)  (0) 2021.03.04
[C#] 확장 메서드, 람다  (0) 2021.01.25
[C#] 암묵적 타입  (0) 2021.01.25
[C#] 스레딩(Threading)  (0) 2021.01.25
[C#] 델리게이트(Delegate)  (0) 2021.01.24

댓글