자동 속성과 구조가 혼합되지 않습니까?
이 게시물에 답변하는 동안 몇 가지 작은 구조를 걷다가 갑자기 다음과 같은 것을 발견했습니다.
int 필드를 사용하는 다음 구조는 완벽하게 합법적입니다.
struct MyStruct
{
public MyStruct ( int size )
{
this.Size = size; // <-- Legal assignment.
}
public int Size;
}
그러나 자동 속성을 사용하는 다음 구조는 컴파일되지 않습니다.
struct MyStruct
{
public MyStruct ( int size )
{
this.Size = size; // <-- Compile-Time Error!
}
public int Size{get; set;}
}
반환 된 오류는 "모든 필드가 할당되기 전에는 'this'개체를 사용할 수 없습니다."입니다. 이것이 구조체의 표준 절차라는 것을 알고 있습니다. 모든 속성의 지원 필드는 구조체의 생성자 내에서 직접 (속성의 집합 접근자를 통해가 아니라) 할당되어야합니다.
해결책은 명시 적 지원 필드를 사용하는 것입니다.
struct MyStruct
{
public MyStruct(int size)
{
_size = size;
}
private int _size;
public int Size
{
get { return _size; }
set { _size = value; }
}
}
(VB.NET에서는 VB.NET에서 모든 필드가 처음 생성 될 때 자동으로 0 / null / false로 초기화되기 때문에이 문제가 발생하지 않습니다.)
이것은 C #에서 구조체와 함께 자동 속성을 사용할 때 불행한 제한으로 보입니다. 개념적으로 생각하면 속성 집합 접근자를 구조체의 생성자 내에서 적어도 자동 속성에 대해 호출 할 수있는 예외가있을 수있는 합리적인 장소가 아닌지 궁금합니다.
이것은 사소한 문제이며 거의 엣지 케이스이지만 다른 사람들이 이것에 대해 어떻게 생각하는지 궁금합니다.
C # 6 이후 : 더 이상 문제가되지 않습니다.
Becore C # 6에서이 작업을 수행하려면 기본 생성자를 호출해야합니다.
public MyStruct(int size) : this()
{
Size = size;
}
여기서 더 큰 문제는 가변 구조체가 있다는 것입니다. 이것은 결코 좋은 생각 이 아닙니다 . 나는 그것을 만들 것이다 :
public int Size { get; private set; }
아니 기술적으로 변경할 수 있지만, 충분히 가까이.
최신 버전의 C #을 사용하면 다음을 개선 할 수 있습니다.
public int Size { get; }
This can now only be assigned in the constructor.
You can fix this by first calling the default constructor:
struct MyStruct
{
public MyStruct(int size) : this()
{
this.Size = size; // <-- now works
}
public int Size { get; set; }
}
Another obscure work-around to this problem is one spotted in the temporary Tuple
class in the Managed Extensibility Framework (via Krzysztof Koźmic):
public struct TempTuple<TFirst, TSecond>
{
public TempTuple(TFirst first, TSecond second)
{
this = new TempTuple<TFirst, TSecond>(); // Kung fu!
this.First = first;
this.Second = second;
}
public TFirst First { get; private set; }
public TSecond Second { get; private set; }
(Full source code from Codeplex: Tuple.cs)
I also note that the documentation for CS0188 has been updated to add:
If you see this error when trying to initialize a property in a struct constructor, the solution is to change the constructor parameter to specify the backing field instead of the property itself. Auto-implemented properties should be avoided in structs because they have no backing field and therefore cannot be initialized in any way from the constructor.
So I take that to mean that the official guidance is to use old-style properties in your structs when you run in to this problem, which is probably less obscure (and more readible) than either of the other two alternatives explored so far.
참고URL : https://stackoverflow.com/questions/420433/automatic-properties-and-structures-dont-mix
'Nice programing' 카테고리의 다른 글
WPF의 숫자 데이터 입력 (0) | 2020.11.21 |
---|---|
C #의 큰 정수 (0) | 2020.11.21 |
어떤 크로스 브라우저 문제에 직면 했습니까? (0) | 2020.11.21 |
SourceTree에서 git-blame은 어디에 있습니까? (0) | 2020.11.21 |
Python 할당을 오버로드 할 수 있습니까? (0) | 2020.11.21 |