C# 7.0μ μλ‘μ΄ κΈ°λ₯
6. μ’ λ£μ(Deconstructor)
μ’ λ£μ(Deconstructor)λ μμ±μ(Constructor)μ λμΉμ μΈ κ°λ μ΄μ§λ§ νκ΄΄μ(Destructor)μλ λ€λ₯΄λ€.
- μμ±μλ λ³΄ν΅ μΈλΆμμ μ λ ₯ νλΌλ―Έν°λ₯Ό λ°μλ€μ¬ μ΄λ₯Ό νλμ μ μ₯νλ μν μ νλ€.
- μ’ λ£μλ νλμ κ°λ€μ μΈλΆλ‘ μ λ¬νλ μν μ νλ€.
- νκ΄΄μλ λΆνμν 리μμ€λ₯Ό μ κ±°νλ μν μ νλ€.
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
BasicInfo person = new BasicInfo(1, "Lee", 10);
var (id, name, age) = person;
WriteLine($"{id} - {name}");
}
}
class BasicInfo
{
private int _id;
private string _name;
private int _age;
// Constructor
public BasicInfo(int id, string name, int age)
{
this._id = id;
this._name = name;
this._age = age;
}
// Deconstructor
public void Deconstruct(out int id, out string name, out int age)
{
id = this._id;
name = this._name;
age = this._age;
}
}
}
7. ref local, ref return
1) ref local
ref localλ λ‘컬 λ³μμ λν΄ refλ₯Ό μ μ©ν κ²μΌλ‘ λμΌν λ©λͺ¨λ¦¬ 곡κ°μ λν λ νΌλ°μ€λ₯Ό λ§νλ€.
int a = 1;
ref int b = ref a; // ref local
b = 2;
WriteLine($"{a}, {b}"); // 2, 2
2) ref return
μ΄μ λ²μ μμλ λ©μλμ μ λ ₯ νλΌλ―Έν°μ λν΄μλ§ refλ₯Ό μ μ©ν μ μμμ§λ§, C# 7.0μμλ ref returnμ μ¬μ©νμ¬ λ¦¬ν΄ νμ μ λν΄μλ νμ©νκ² λμλ€. μ΄ refλ ν° μ©λμ λ°μ΄ν°μμ νΉμ μμλ₯Ό 리ν΄νμ¬ μ½κ±°λ λ³κ²½ν λ μ μ©νλ€.
using static System.Console;
namespace ConsoleApp1
{
class Program
{
static GameData _gameData = new GameData();
static void Main(string[] args)
{
ref int score10 = ref _gameData.GetScore(10);
score10 = 99;
WriteLine(_gameData.GetScore(10)); // 99
}
}
class GameData
{
private int[] scores = new int[100];
// ref return
public ref int GetScore(int id)
{
return ref scores[id];
}
}
}