gpt4 book ai didi

c# - 构造函数未被调用

转载 作者:行者123 更新时间:2023-11-30 13:25:57 26 4
gpt4 key购买 nike

public class Unit
{
public int UnitId { get; set; }
public Engine EngineStuff { get; set; }

}
public class Engine
{
public int PS { get; set; }
public int MaxSpeed { get; set; }
}

var unit = new Unit();
unit.UnitId = 3; //OK because Unit-constructor was called
unit.EngineStuff.PS = 200; //error, because EngineStuff-constructor obviously wasn't called.

如何调用这个“内部”构造函数?我以为它会自动初始化它?

我怎样才能简单地为“EngineStuff.PS”属性赋值?

最佳答案

您必须显式实例化对象的属性:

public class Unit
{
public Unit()
{
EngineStuff = new Engine();
}
}

或者如果您想手动控制何时实例化:

var unit = new Unit();
unit.UnitId = 3;
unit.EngineStuff = new Engine();
unit.EngineStuff.PS = 200;

或更简单:

var unit = new Unit { UnitId = 3 };
unit.EngineStuff = new Engine { PS = 200 };

关于c# - 构造函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34969478/

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