【问题标题】:There is no argument given that corresponds to the required formal parameter 'id' of 'Human.Human(int, string, string, string)'没有给出与 'Human.Human(int, string, string, string)' 的所需形式参数 'id' 相对应的参数
【发布时间】:2019-01-15 17:24:37
【问题描述】:

我无法从 Homecontrollers 操作方法调用新的 Human 对象。

        var employee = new Human { id = 1, name = "home index" , isAuth = isAuth,token="null"};

这是我的模特

namespace WebApplication3.Models
{
    public class Human
    {
        public Human(int id, string name, string isAuth, string token)
        {
            this.id = id;
            this.name = name;
            this.isAuth = isAuth;
            this.token = token;
        }

【问题讨论】:

  • 应该像 new Human( id = 1, name = "home index" , isAuth = isAuth,token="null");构造函数使用第一轮而不是花括号。
  • 或者添加一个空的构造函数(前提是那些属性是公共的)
  • @Gaurav,您不能使用“=”来命名参数。 var employee = new Human (id: 1, name: "home index", isAuth: isAuth, token: "null");var employee = new Human (1, "home index", isAuth, "null");

标签: c# .net


【解决方案1】:

您正在使用Object Initializer 的语法,但此语法至少需要使用一个空的构造函数,因为花括号内的代码是在构造对象之后执行的。

如果您想使用该语法,您需要将一个 emtpy 构造函数添加到您的模型中

public class Human
{
    public Human() {}

    public Human(int id, string name, string isAuth, string token)
    {
        this.id = id;
        this.name = name;
        this.isAuth = isAuth;
        this.token = token;
    }

现在你有两个选择。使用当前语法,以便编译器调用空构造函数,然后使用大括号之间的值初始化属性,或者使用正常语法直接调用具有四个参数的构造函数。

var employee = new Human (1,"home index",isAuth,"null");

请注意,对于第一种方法,您需要将这些属性公开

public class Human
{
    public int id {get;set;}           
    .....

【讨论】:

    【解决方案2】:

    试试这个

    var employee = new Human(1, "home index" isAuth, null); 
    

    【讨论】:

    • var employee = new Human(id: 1, name: "home index", isAuth: isAuth, token: null);,如果它有助于提高可读性,请使用冒号。
    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 2019-10-11
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2019-08-09
    相关资源
    最近更新 更多