'Contact'不包含带3个参数的构造函数 [英] 'Contact' does not contain a constructor that takes 3 arguments
问题描述
您好!我正在尝试制作电话簿程序。我希望通过以下行添加联系人:
Hello! I'm trying to make a phonebook program. I want to add a contact by this line:
Contact person = new Contact("Bob", "Smith", "0500399");
问题是我收到错误说
The problem is that I get an error saying
'Contact' does not contain a constructor that takes 3 arguments
我的'联系'课程如下:
My 'Contact' class looks like this:
class Contact
{
public string FristName { get; private set; }
public string LastName { get; private set; }
public string PhoneNr { get; private set; }
public void CreateContact (string firstname, string lastname, string phonenr)
{
this.FristName = firstname;
this.LastName = lastname;
this.PhoneNr = phonenr;
}
}
我知道我可以通过这样做来设置这些值
I know that I could set these values by doing
person.CreateContact("Bob", "Smith", "0500399")
这不是我想要的。我想在制作实例的同时添加它。
我是编程的新手,所以请耐心等待。提前谢谢: - )
This is not what I want. I want to add it the same time I make the instance.
I'm new to programming, so please bear with me. Thank you in advance :-)
推荐答案
为什么不让类的构造函数获取参数:
Why don't you just make the Constructor of the Class take parameters:
public Contact(string firstname, string lastname, string phonenr)
{
this.FristName = firstname;
this.LastName = lastname;
this.PhoneNr = phonenr;
}
当然,如果你这样做,你真的不需要单独的'CreateContact方法。
如果你期望某些联系人没有电话号码,您可以将该参数设为可选:
Of course, if you do that, you really don't need a separate 'CreateContact method.
If you expect that some contacts will not have a phone number, you can make that parameter optional:
public Contact(string firstname, string lastname, string phonenr = "")
{
this.FristName = firstname;
this.LastName = lastname;
this.PhoneNr = phonenr;
}
要稍微修复Bills代码(他实际上没有添加构造函数!),你的Contact类看起来会更像这样:
To fix Bills code a bit (he didn't actually add a constructor!), your Contact class would look more like this:
public class Contact
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string PhoneNr { get; private set; }
// A public constructor
public Contact(string firstName, string lastName, string phoneNr)
{
this.FirstName = firstName;
this.LastName = lastName;
this.PhoneNr = phoneNr;
}
// CreateContact should return a new Contact object.
// That's what Create... implies.
// You'd use it like this:
// Contact myContact = Contact.CreateContact(f, l, p);
public static Contact CreateContact(string firstName, string lastName, string phoneNr)
{
Contact newContact = new Contact(firstname, lastname, phonenr);
return newContact;
}
}
这篇关于'Contact'不包含带3个参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!