不包含带2个参数的构造函数?

我目前正在做一些类编码,并想知道我的项目出了什么问题?

class ContactPerson { string name; ContactNo telNo; public ContactPerson(string in_Name, ContactNo in_No) { name = in_Name; telNo = new ContactNo(); } public string getName() { return name; } public ContactNo getContactInfo() { return telNo; } public void setName(string in_Name) { name = in_Name; } public void setContactInfo (ContactNo in_No) { telNo = in_No; } } 

}

 class ContactNo { string contactType; string contactNo; public void setContactType(string in_Type) { contactType = in_Type; } public string getContactType() { return contactType; } public void setContactNo(string in_No) { contactNo = in_No; } public string getContactNo() { return contactNo; } } 

}

 class Program { static void Main(string[] args) { ContactNo telNo; telNo = new ContactNo("Mobile No: ", 95656565); ContactPerson myFriend; myFriend = new ContactPerson("Fred Smith", telNo); string strName; strName = myFriend.getName(); Console.WriteLine(" " + strName); ContactNo outContact; outContact = myFriend.getContactInfo(); outContact.getContactType(); Console.WriteLine(outContact); outContact.getContactNo(); Console.WriteLine(outContact); Console.ReadLine(); } } 

}

在程序类“telNo = new ContactNo(”Mobile No:“,95656565);”theres错误说不包含带有2个参数的构造函数我可能知道为什么?

那是因为你没有在ContactNo类中包含两个参数的构造函数,正如错误所示。 看看课程,你会发现那里没有构造函数。 但是,你在ContactPerson类中有一个。

这一行: telNo = new ContactNo("Mobile No: ", 95656565); 正在调用ContactNo的构造函数,它接受两个参数:一个字符串和一个int。 您没有设置为当前执行此操作的构造函数,而这正是您的错误所在。 您可以通过添加创建一个

 public ContactNo(string s, int n){ //initializations } 

或者那种性质的东西。 或者,如果您使用字符串作为数字(它看起来像),请将int n替换为string s2或您想要调用它的任何内容。

因为你没有联系没有2个参数的构造函数。 我猜你会把它与你的其他有2个参数的类混淆

 public ContactPerson(string in_Name, ContactNo in_No) 

从您的代码看起来您​​必须将其添加到您的类ContactNo

  public ContactNo(string type, string umber) { contactType = type; contactNo = number; } 
 public ContactNo(string type, string umber) { contactType = type; contactNo = number; } 

在ContactNo类中添加此项。

你得到错误的原因是因为没有带两个参数的构造函数。

将以下内容添加到您的ContactNo类:

 public ContactNo(string inType, string inNo) { contactType = inType; contactNo = inNo; } 

你没有构造函数来获取2个参数。 在ContactNo类中添加此构造函数

 public ContactNo(string contactType, string contactNo) { this.contactType = contactType; this.contactNo = contactNo; } 

您需要声明ContactNo类的构造函数。 类只提供没有参数的默认构造函数。

您需要的构造函数如下:

 public ContactNo(string contactType, string contactNo) { this.contactType = contactType; this.contactNo = contactNo; } 

因为你传递一个stringint我认为你想创建一个新的ContactPerson ,而不是ContactNo 。 但是,如果您真的想要ContactNo ,请添加构造函数:

class ContactNo {public string ContactType {get; 组; public字符串ContactNo {get; 组; }

 public ContactNo(string type, string no) { ContactType = type; ContactNo = no; } 

}

或者(使用属性)将其初始化为:

 ContactNo contact = { ContactType = "The type", ContactNo = "The No" };