代码之家  ›  专栏  ›  技术社区  ›  John D

初始化classObject=new()时出现编译错误;

  •  0
  • John D  · 技术社区  · 2 年前

    在我们的.NET REST-API中,我有一个DTO类和一个C#控制器类。 DTO类如下所示,没有任何编译错误。 该DTO包含一个用于检查的变量和一个用于在检查期间观察到的缺陷列表的IEnumerable/list变量。当没有缺陷时,“列表”可能为空。这类似于增加具有多个发票项目的发票的安排。

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

    这是我初始化的控制器功能代码 PTInspectionAndTMDefectsDTO createdInspectionAndDefects 使用提供所需PTInspection变量的第一构造函数。最后一个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...
    

    enter image description here

    错误CS9035没有进一步的信息。 我不知道为什么 new(createdInspection); 无效。欢迎您的协助。谢谢约翰

    1 回复  |  直到 2 年前
        1
  •  2
  •   Gabor    2 年前

    你需要用 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;
        }
    }
    

    请注意:

    是否应该有一个不设置所有 必需 属性则不使用标记该ctor [SetsRequiredMembers]

    推荐文章