C#
C# -- property (속성) 사용법
자유프로그램
2019. 3. 16. 15:33
반응형
C# -- property (속성) 사용법
참고: http://www.csharpstudy.com/CS6/CSharp-auto-property.aspx
** 읽기전용 속성에 값 입력 2가지 경우.
--> 1. 생성자 에서 가능.
2. 자동속성초기화
< 실행화면 >
< 소스 >
--
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace property_test | |
{ | |
class Person | |
{ | |
public string Name { get; set;} | |
public int Age { get; } // 읽기전용, 생성자, 자동속성초기화 에서만 쓰기 접근가능. | |
public int grade { get; } = 5; // 자동속성초기화 | |
public Person(string name, int age) | |
{ | |
this.Name = name; | |
this.Age = age; | |
} | |
public void SetAge(int newAge) | |
{ | |
//this.Age = newAge; // error!!!! | |
} | |
public override string ToString() | |
{ | |
return $"name={Name}, age={this.Age}, grade={grade}"; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Person a = new Person("Tom", 14); | |
Console.WriteLine(a); | |
//a.Age = 33; // error!!!! | |
Console.ReadKey(); // 아무키나 누르면 종료. | |
} | |
} | |
} |
반응형