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

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

问题描述

下面是一个结构,我尝试写:

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:

的这个对象不能被用于
  之前所有字段被分配
  到

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.

我在做什么错了?

推荐答案

您正在设置概率通过概率场属性,但是编译器不知道该属性设置现场...所以你需要明确初始化概率字段本身

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;
}

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

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