[C#] Property

– public member field보다는 property를 이용하는 편이 낫다.

다음과 같은 클래스에 대해서

[code language=”csharp”]
class Namecard{
public string name;

}

[/code]

name을 not null로 만들기 위해서는 여러 코드를 고쳐야한다. 그러나 프로퍼티를 이용하면,

[code language=”csharp”]
class Namecard{
private string name;
public string Name{
get { return name; }
set {
if(value == null)
throw new ArgumentException("Name cannot be null");
name = value;
}
}

}
[/code]

와 같이 한 곳만 고치면 된다.

– 프로퍼티는 메서드의 특징을 가지므로 virtual로 선언이 가능하다. 또, lock을 통해서 메서드가 데이터에 동기적으로 접근할 수 있도록 만들 수 있다.

– 프로퍼티는 인터페이스의 멤버가 될 수 있다. 그러므로 다음과 같이 non-const 형식의 프로퍼티와 const형식(readonly)으로 사용할 수 있다.

[code language=”csharp”]

using System;

namespace CSharpConsole
{
class Program
{
static void Main(string[] args)
{
Complex comp = new Complex(3, 5);
Console.WriteLine(comp);
IComplex comp1 = comp;
comp1.Imag = -3;
Console.WriteLine(comp);
IConstComplex comp2 = comp;
///// comp2.Imag = 4; // Compile Error
}
}

interface IComplex
{
decimal Real { get; set; }
decimal Imag { get; set; }
}

interface IConstComplex
{
decimal Real { get; }
decimal Imag { get; }
}

class Complex : IComplex, IConstComplex
{
decimal realPart;
decimal imagPart;

#region IComplex
decimal IComplex.Real
{
get { return realPart; }
set { realPart = value; }
}

decimal IComplex.Imag
{
get { return imagPart; }
set { imagPart = value; }
}
#endregion

#region IConstComplex
decimal IConstComplex.Real
{
get { return realPart; }
}

decimal IConstComplex.Imag
{
get { return imagPart; }
}
#endregion

public Complex(decimal real = 0, decimal imag = 0)
{
realPart = real;
imagPart = imag;
}

public override string ToString()
{
return string.Format("({0}{1}{2}j)",
realPart, imagPart < 0 ? "" : "+", imagPart);
}
}
}
[/code]

– 프로퍼티에 접근 한정자(private, protected, public)을 지정할 수 있다.

– 프로퍼티는 사용하는 방법이 일반 멤버필드와 비슷하지만, IL코드로 나타내면, 프로퍼티라는 객체에 set, get메서드가 구현되는 것이다.
멤버필드에 직접 대입하거나 불러오는 것보다 느릴수 있지만, 일반적으로 프로퍼티는 인라인으로 처리되고 메서드 하나를 불러오는 정도가 걸린다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다