gpt4 book ai didi

c# - 结构构造函数 : "fields must be fully assigned before control is returned to the caller."

转载 作者:IT王子 更新时间:2023-10-29 03:35:22 26 4
gpt4 key购买 nike

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

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

这会导致以下编译错误:

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

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

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.

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.

我做错了什么?

最佳答案

如果您在具有自动属性的结构上看到此错误,只需通过下面的 : this() 示例从您的参数化构造函数调用无参数构造函数:

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

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

通过从构造函数声明中调用 :this(),您可以让基 ValueType 类初始化自动属性的所有支持字段。我们不能在构造函数上手动执行此操作,因为我们无权访问自动属性的支持字段。ValueType 是所有结构的基类。

关于c# - 结构构造函数 : "fields must be fully assigned before control is returned to the caller.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2534960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com