Construct (생성자) 오버로딩
- C# Study/C# 케이스 스터디
- 2019. 12. 12. 23:52
문제점
생성자를 이용하여 초기화할 때, 직접 초기화하고 싶지 않은 값들이 있다.
선택적 매개 변수를 사용하면 어떨까?
선택적 매개변수를 사용한다면 다음과 같은 형식이 된다.
public StatModifier(float value, StatModType type, int order = 1, object source = null)
{
Value = value;
Type = type;
Order = order;
Source = source;
}
하지만 선택적 매개변수는 모든 필수 매개변수 다음에 와야한다는 규칙이 있기 때문에 유연하지 못하다.
생성자 오버로딩!
생성자를 오버로딩해서 만들어두면, 입력받은 매개변수로
다른매개변수를 할당하는 등 꽤나 유연한 생성이 가능하다.
public class StatModifier
{
public readonly float Value;
public readonly StatModType Type;
public readonly int Order; // 덧셈을 먼저 계산한다.
public readonly object Source;
public StatModifier(float value, StatModType type, int order, object source)
{
Value = value;
Type = type;
Order = order;
Source = source;
}
public StatModifier(float value, StatModType type) : this(value, type, (int)type, null) { }
public StatModifier(float value, StatModType type, int order) : this(value, type, order, null) { }
public StatModifier(float value, StatModType type, object source) : this(value, type, (int)type, source) { }
}
매개 변수를 사용하지않는 초기화는 아래와 같이도 가능하다.
public CharacterStat()
{
statModifers = new List<StatModifier>();
StatModifers = statModifers.AsReadOnly();
}
public CharacterStat(float baseValue) : this()
{
BaseValue = baseValue;
}
'C# Study > C# 케이스 스터디' 카테고리의 다른 글
C# Collection Foreach 에서 원소 삭제하기 (0) | 2019.12.15 |
---|---|
C# params 키워드 : 가변 개수의 인수 (0) | 2019.12.13 |
ReadOnlyCollection (0) | 2019.12.12 |
for 문에서 AddListener 람다식은 주의해야한다. (AddListener for loop) 클로저 Closure problem (5) | 2019.12.12 |
List<T> Sort (0) | 2019.12.10 |