일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- git
- c# 추상 클래스
- jupyter
- C언어 포인터
- C# delegate
- 도커
- github
- 다트 언어
- Unity
- c# 윈폼
- c언어
- Data Structure
- HTML
- 구조체
- c#
- gitlab
- Python
- 깃
- docker
- jupyter lab
- 포인터
- dart 언어
- 유니티
- Flutter
- 플러터
- Houdini
- vim
- C++
- Algorithm
- c# winform
Archives
- Today
- Total
07-05 07:53
nomad-programmer
[Programming/C#] 프로퍼티와 생성자 본문
프로퍼티를 이용한 초기화는 다음과 같다.
클래스이름 인스턴스 = new 클래스이름()
{
프로퍼티1 = 값,
프로퍼티2 = 값,
프로퍼티3 = 값
}
객체를 생성할 때 <프로퍼티 = 값> 목록에 객체의 모든 프로퍼티가 올 필요는 없다. 초기화하고 싶은 프로퍼티만 넣어서 초기화하면 된다.
매개 변수가 있는 생성자를 작성할 때와는 달리 어떤 필드를 생성자 안에서 초기화할지를 미리 고민할 필요가 없다.
using System;
namespace CSharpExample
{
class MainApp
{
class BirthdayInfo
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public int Age
{
get
{
return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
}
}
}
static int Main(string[] args)
{
BirthdayInfo birth = new BirthdayInfo()
{
Name = "김연아",
Birthday = new DateTime(1990, 09, 05)
};
Console.WriteLine($"Name : {birth.Name}");
Console.WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
Console.WriteLine($"Age : {birth.Age}");
return 0;
}
}
}
/* 결과
Name : 김연아
Birthday : 9/5/1990
Age : 31
*/
'Programming > C#' 카테고리의 다른 글
[Programming/C#] 인터페이스의 프로퍼티 (0) | 2020.09.14 |
---|---|
[Programming/C#] 무명 형식의 프로퍼티 (0) | 2020.09.14 |
[Programming/C#] 자동 구현 프로퍼티 (0) | 2020.09.12 |
[Programming/C#] 프로퍼티 (Property) (0) | 2020.09.11 |
[Programming/C#] 추상 클래스2 (interface와 class 사이) (0) | 2020.09.11 |
Comments