在我们的 .NET REST-API 中,我有一个 DTO 类和一个 C# 控制器类。 DTO 类如下,没有任何编译错误。 该 DTO 包含一个用于检查的变量和一个用于检查期间观察到的缺陷列表的 IEnumerable/list-variable。当没有缺陷时,“列表”可能为空。这类似于添加具有多个发票项目的发票的排列。
public class PTInspectionAndTMDefectsDTO {
public required PTINSPECTION PtInspection { get; set; }
public IEnumerable<TMDEFECT> TMDefects { get; set; } = Enumerable.Empty<TMDEFECT>();
// Constructors.
public PTInspectionAndTMDefectsDTO(PTINSPECTION ptinspection) { PtInspection = ptinspection; }
public PTInspectionAndTMDefectsDTO(PTINSPECTION ptinspection, IEnumerable<TMDEFECT> tmdefects) { PtInspection = ptinspection; TMDefects = tmdefects; }
}
这是控制器功能代码,我使用提供所需 PTInspection 变量的第一个构造函数来初始化
PTInspectionAndTMDefectsDTO createdInspectionAndDefects
。最后一个 C# 语句中出现编译错误。
[HttpPost("AddPTInspectionAndDefects")]
public async Task<IActionResult> AddPTInspectionAndDefects([FromBody] PTInspectionAndTMDefectsDTO oDataToAdd) {
PTINSPECTION addThisInspection = oDataToAdd.PtInspection;
IEnumerable<TMDEFECT>? addTheseDefects = oDataToAdd.TMDefects;
PTINSPECTION createdInspection = new PTINSPECTION();
TMDEFECT? createdDefect = new TMDEFECT();
IEnumerable<TMDEFECT> createdDefectList = Enumerable.Empty<TMDEFECT>();
PTInspectionAndTMDefectsDTO createdInspectionAndDefects = new(createdInspection);
... a compilation error appears for the above sentence with a red-squiggle under the word [new] -- see image below.
... other code is not provided...
错误CS9035没有更多信息。 我不确定为什么
new(createdInspection);
无效。欢迎您的帮助。谢谢...约翰
SetsRequiredMembersAttribute
标记演员。
否则,您必须在对象初始值设定项中设置
required
属性。
using System.Diagnostics.CodeAnalysis;
public class PTInspectionAndTMDefectsDTO
{
public required PTINSPECTION PtInspection { get; set; }
public IEnumerable<TMDEFECT> TMDefects { get; set; } = Enumerable.Empty<TMDEFECT>();
// Constructors.
[SetsRequiredMembers]
public PTInspectionAndTMDefectsDTO(PTINSPECTION ptinspection)
{
PtInspection = ptinspection;
}
[SetsRequiredMembers]
public PTInspectionAndTMDefectsDTO(PTINSPECTION ptinspection, IEnumerable<TMDEFECT> tmdefects)
{
PtInspection = ptinspection;
TMDefects = tmdefects;
}
}