C# 不包含接受2个参数的构造函数?
我目前正在做一些类编码,想知道我的项目出了什么问题C# 不包含接受2个参数的构造函数?,c#,class,C#,Class,我目前正在做一些类编码,想知道我的项目出了什么问题 class ContactPerson { string name; ContactNo telNo; public ContactPerson(string in_Name, ContactNo in_No) { name = in_Name; telNo = new ContactNo(); } public string getName() {
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;
}
}
}
}
}
在节目课上
telNo=新联系人号码(“手机号码:,956565”)
错误说明不包含接受2个参数的构造函数
我可以知道原因吗?这可能是因为您没有一个构造函数在ContactNo类中包含两个参数,正如错误所示。看看这个类,你会发现里面没有构造函数。不过,ContactPerson类中确实有一个 该行:
telNo=newcontactno(“手机号码:”,956565)代码>
正在调用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;
}
将此添加到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;
}
由于您正在传递一个字符串
和int
,因此我认为您希望创建一个新的联系人
,而不是联系人编号
。但是,如果确实需要ContactNo
,请添加构造函数:
class ContactNo
{
public string ContactType { get; set; }
public string ContactNo { get; set; }
public ContactNo(string type, string no)
{
ContactType = type;
ContactNo = no;
}
}
或者(使用属性)按如下方式初始化它:
ContactNo contact = { ContactType = "The type", ContactNo = "The No" };
来自爪哇,对吗?请使用而不是getABC()
和setABC()
方法。要详细说明@HighCore所说的内容,请使用公共字符串YourString{get{return}YourString}set{YourString=value};然后可以使用属性初始值设定项:telNo=newcontactno(){ContactType=“Mobile No:”,Number=956565}
@HighCore当我从Java亲自来到C时,这让我非常高兴也要强烈地考虑把匈牙利符号留在那里…过去。
public ContactNo(string contactType, string contactNo) {
this.contactType = contactType;
this.contactNo = contactNo;
}
class ContactNo
{
public string ContactType { get; set; }
public string ContactNo { get; set; }
public ContactNo(string type, string no)
{
ContactType = type;
ContactNo = no;
}
}
ContactNo contact = { ContactType = "The type", ContactNo = "The No" };