Programing

구조체 생성자 : "컨트롤이 호출자에게 반환되기 전에 필드가 완전히 할당되어야합니다."

lottogame 2020. 8. 12. 22:06
반응형

구조체 생성자 : "컨트롤이 호출자에게 반환되기 전에 필드가 완전히 할당되어야합니다."


다음은 작성하려는 구조체입니다.

  public struct AttackTraits
        {
            public AttackTraits(double probability, int damage, float distance)
            {
                Probability = probability;
                Distance = distance;
                Damage = damage;
            }

            private double probability;
            public double Probability
            {
                get
                {
                    return probability;
                }
                set
                {
                    if (value > 1 || value < 0)
                    {
                        throw new ArgumentOutOfRangeException("Probability values must be in the range [0, 1]");
                    }
                    probability = value;
                }
            }

            public int Damage { get; set; }

            public float Distance { get; set; }
        }

이로 인해 다음 컴파일 오류가 발생합니다.

'this'개체는 모든 필드가 할당되기 전에는 사용할 수 없습니다.

컨트롤이 호출자에게 반환되기 전에 'AttackTraits.probability'필드를 완전히 할당해야합니다.

자동으로 구현 된 속성 'AttackTraits.Damage'에 대한 지원 필드는 제어가 호출자에게 반환되기 전에 완전히 할당되어야합니다. 생성자 이니셜 라이저에서 기본 생성자를 호출하는 것을 고려하십시오.

자동으로 구현 된 속성 'AttackTraits.Distance'에 대한 지원 필드는 제어가 호출자에게 반환되기 전에 완전히 할당되어야합니다. 생성자 이니셜 라이저에서 기본 생성자를 호출하는 것을 고려하십시오.

내가 뭘 잘못하고 있죠?


속성을 probability통해 필드를 설정하고 Probability있지만 컴파일러는 속성이 필드를 설정한다는 사실을 모르기 때문에 확률 필드 자체를 명시 적으로 초기화해야합니다.

public AttackTraits(double probability, int damage, float distance)
{
    this.probability = 0;
    Distance = distance;
    Damage = damage;
}

자동 속성이있는 구조체에서이 오류가 표시되면 : this()아래 예제 를 수행하여 매개 변수화 된 구성자에서 매개 변수없는 생성자를 호출하기 만하면 됩니다.

struct MyStruct
{
  public int SomeProp { get; set; }

  public MyStruct(int someVal) : this()
  {
     this.SomeProp = someVal;
  }
}

생성자 선언에서 : this ()를 호출하면 기본 ValueType 클래스가 자동 속성에 대한 모든 지원 필드를 초기화 할 수 있습니다. 자동 속성의 지원 필드에 액세스 할 수 없기 때문에 생성자에서 수동으로 수행 할 수 없습니다. ValueType은 모든 구조체의 기본 클래스입니다.


접근자가 아닌 확률 필드에 액세스하십시오. 이 경우 자동 소품도 작동합니다.

There is no way for a struct to have parameterless constructor so consider change it to class instead.

Best practise is to use structs only if they are 16 bytes or less and are immutable. So if you are going to change object fields after creating, consider refactoring it to class.

Also, you can change constructor definition to:

construct(params) : this()

this will remove error as well


Change the line Probability = probability to this.probability = probability

In the future pick a different naming convention for fields as you do for parameters. For example, prefix all fields with an underscore, so you can simply call this:

_probability = probability;

and see easily what's happening.

참고URL : https://stackoverflow.com/questions/2534960/struct-constructor-fields-must-be-fully-assigned-before-control-is-returned-to

반응형