结构构造函数:“在将控制权返回给调用者之前,必须完全分配字段." [英] Struct constructor: "fields must be fully assigned before control is returned to the caller."

查看:23
本文介绍了结构构造函数:“在将控制权返回给调用者之前,必须完全分配字段."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在尝试编写的结构:

Here is a struct I am trying to write:

  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 results in the following compilation errors:

不能使用'this'对象在分配所有字段之前

The 'this' object cannot be used before all of its fields are assigned to

字段 'AttackTraits.probability' 必须在控制之前被完全分配返回给调用者

Field 'AttackTraits.probability' must be fully assigned before control is returned to the caller

自动支持字段实现的财产'AttackTraits.Damage' 必须完全在控制权返回之前分配呼叫者,召集者.考虑调用来自构造函数的默认构造函数初始化程序.

Backing field for automatically implemented property 'AttackTraits.Damage' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

自动支持字段实现的财产'AttackTraits.Distance' 必须完全在控制权返回之前分配呼叫者,召集者.考虑调用来自构造函数的默认构造函数初始化程序.

Backing field for automatically implemented property 'AttackTraits.Distance' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

我做错了什么?

推荐答案

您正在通过 Probability 属性设置 probability 字段,但编译器不知道该属性设置字段...因此您需要显式初始化概率字段本身

You're setting the probability field through the Probability property, but the compiler doesn't know that the property sets the field... so you need to explicitly initialize the probability field itself

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

这篇关于结构构造函数:“在将控制权返回给调用者之前,必须完全分配字段."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆