읽기 전용 속성을 구현하는 방법
내 유형에 읽기 전용 속성 을 구현해야 합니다. 또한이 속성의 값은 생성자에서 설정되며 변경되지 않습니다 (WPF에 대한 사용자 지정 라우팅 UI 명령을 노출하는 클래스를 작성하고 있지만 중요하지 않습니다).
두 가지 방법이 있습니다.
class MyClass { public readonly object MyProperty = new object(); }
class MyClass { private readonly object my_property = new object(); public object MyProperty { get { return my_property; } } }
이 모든 FxCop 오류가 퍼블릭 멤버 변수를 가져서는 안된다는 오류와 함께 두 번째가 올바른 방법 인 것 같습니다. 옳은?
이 경우 가져 오기 전용 속성과 읽기 전용 멤버간에 차이점이 있습니까?
나는 어떤 의견 / 조언 / 등을 감사 할 것입니다.
버전 관리 :
소스 호환성에만 관심이 있다면 큰 차이가 없다고 생각합니다.
속성을 사용하면 라이브러리에 따라 컴파일 된 코드를 손상시키지 않고 setter가있는 속성으로 대체 할 수 있으므로 바이너리 호환성에 더 좋습니다.
대회 : 대회
를 따르고 있습니다. 이와 같은 경우 두 가지 가능성의 차이가 관례에 따라 상대적으로 작은 경우가 더 좋습니다. 다시 물릴 수있는 한 가지 경우는 반사 기반 코드입니다. 속성 편집기 / 뷰어와 같이 필드가 아닌 속성 만 허용 할 수 있습니다.
Serialization
필드에서 속성으로 변경하면 많은 serializer가 손상 될 수 있습니다. 그리고 AFAIK XmlSerializer
는 공용 필드가 아닌 공용 속성 만 직렬화합니다.
Autoproperty 사용
또 다른 일반적인 변형은 private setter와 함께 autoproperty를 사용하는 것 입니다. 이것은 짧고 속성이지만 읽기 전용을 강제하지 않습니다. 그래서 나는 다른 것을 선호합니다.
읽기 전용 필드는 자체 문서화
입니다. 그러나 필드의 한 가지 장점이 있습니다
. 공개 인터페이스에서 실제로 변경 불가능하다는 것을 한 눈에 분명히 보여줍니다 (반사를 제외하고). 속성의 경우, 반면 만 볼 수 있습니다 당신은 당신이 문서 또는 구현을 참조해야 할 것이다, 그래서 그것을 변경할 수 없습니다.
그러나 솔직히 나는 게으 르기 때문에 응용 프로그램 코드에서 첫 번째를 자주 사용합니다. 도서관에서는 일반적으로 더 철저하고 규칙을 따릅니다.
C # 6.0은 읽기 전용 자동 속성을 추가합니다.
public object MyProperty { get; }
따라서 이전 컴파일러를 지원할 필요가 없을 때 읽기 전용 필드만큼 간결한 코드로 진정한 읽기 전용 속성을 가질 수 있습니다.
두 번째 방법은 선호하는 옵션입니다.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
이렇게하면 MyVal
초기화시에만 할당 할 수 있습니다 (생성자에서도 설정할 수 있음).
앞서 언급했듯이-이렇게하면 내부 구성원을 노출하지 않으므로 나중에 내부 구현을 변경할 수 있습니다.
C # 6 (VS 2015)의 도입으로 이제 get
암시 적 지원 필드가있는 자동 속성 만 가질 readonly
수 있습니다 (즉, 값은 생성자에서 할당 할 수 있지만 다른 곳에서는 할당 할 수 없음).
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
이제 속성 (setter 포함 또는 제외)을 인라인으로 초기화 할 수도 있습니다.
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in @CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
You can do this:
public int Property { get { ... } private set { ... } }
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
참고URL : https://stackoverflow.com/questions/3917796/how-to-implement-a-read-only-property
'Development Tip' 카테고리의 다른 글
앵커 링크 내부의 버튼은 Firefox에서 작동하지만 Internet Explorer에서는 작동하지 않습니까? (0) | 2020.10.28 |
---|---|
이름으로 저장 프로 시저 찾기 (0) | 2020.10.28 |
루비 클래스 상속 :`<<`(두 배 미만)이란 무엇입니까? (0) | 2020.10.28 |
ggplot에서 종횡비를 수정하는 방법은 무엇입니까? (0) | 2020.10.28 |
PHP에서 이미지 크기 조정 (0) | 2020.10.28 |