【问题标题】:Does not contain a constructor that takes 2 arguments不包含带 2 个参数的构造函数
【发布时间】:2012-12-24 02:40:15
【问题描述】:

我不确定这里发生了什么。该模型是从数据库中自动生成的,我看不到任何明显的东西(请注意,现在是英国时间凌晨 2.30 点,所以也许我睡着了)。我收到错误消息:ActiveCitizenSystemMimic.Models.ActiveCitizenProperties 不包含采用 2 个参数的构造函数。

型号:

namespace ActiveCitizenSystemMimic.Models
{
    using System;
    using System.Collections.Generic;

    public partial class ActiveCitizenProperties
    {
        public int FK_ActiveCitizen { get; set; }
        public int FK_PropertyType { get; set; }
    }
}

控制器:

List<ActiveCitizenProperties> activeCitizenProperties = new List<ActiveCitizenProperties>();
activeCitizenProperties.Add(new ActiveCitizenProperties(1, 2));

【问题讨论】:

    标签: c# .net asp.net-mvc compiler-errors


    【解决方案1】:

    您可以将代码替换为:

    List<ActiveCitizenProperties> activeCitizenProperties = new List<ActiveCitizenProperties>();
    activeCitizenProperties.Add(new ActiveCitizenProperties(){ FK_ActiveCitizen = 1, FK_PropertyType = 2 });
    

    您的“自动生成”类显然不包含带有 2 个参数的构造函数。如果有,应该是这样的:

    namespace ActiveCitizenSystemMimic.Models
    {
        using System;
        using System.Collections.Generic;
    
        public partial class ActiveCitizenProperties
        {
            public int FK_ActiveCitizen { get; set; }
            public int FK_PropertyType { get; set; }
    
            public ActiveCitizenProperties(int a, int b)
            {
                this.FK_ActiveCitizen = a;
                this.FK_PropertyType = b;
            }
        }
    }
    

    【讨论】:

    • 完美。也感谢您的解释。
    【解决方案2】:

    错误的意思是:ActiveCitizenProperties 构造函数不接受两个参数。在给定的代码中,类中根本没有定义构造函数。

    你可以使用:

    new ActiveCitizenProperties { FK_ActiveCitizen = 1, FK_PropertyType = 2 };
    

    【讨论】:

    • 感谢 abatishchev。我还需要确保按照 Alvin Wong 的回答,我有括号。
    • @user975516:你的意思是new ActiveCitizenProperties() { } 而不仅仅是new ActiveCitizenProperties { }?它们不是必需的,例如 Resharper 会提示省略它们。
    猜你喜欢
    • 1970-01-01
    • 2013-02-17
    • 2012-08-21
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2011-10-05
    相关资源
    最近更新 更多