[英]C# Create an object and add to a list
I have a basic csharp objects question.我有一个基本的 csharp 对象问题。 I want to add my emails to a list and display their content.
我想将我的电子邮件添加到列表中并显示其内容。
I have created my object class:我已经创建了我的 object class:
public class Email{
public string EmailSubject {get; set;}
public string EmailContent {get; set;}
public Email(String Subject, String Content)
{
EmailSubject = Subject;
EmailContent = Content;
}
Then I want to create a list and start making object to add to them and display.然后我想创建一个列表并开始制作 object 以添加到它们并显示。
List<Email> Emails = new List<Email>();
Emails.Add(new Email() {EmailSubject="MySubject", EmailContent="MyContent"} );
Console.WriteLine();
foreach (Email e in Emails)
{
Console.WriteLine(e);
}
However, I am getting this error:但是,我收到此错误:
There is no argument given that corresponds to the required formal parameter 'Subject' of 'Email.Email(string, string)'
I have also attempted to do this我也尝试过这样做
Emails.Add(new Email(EmailSubject="MySubject", EmailContent="MyContent" ));
but my out is simply Email
但我的输出只是
Email
What am i doing wrong?我究竟做错了什么?
you are trying to call parameterless constructor in new new Email() and its not specified您正在尝试在 new new Email() 中调用无参数构造函数,但未指定
you can just add你可以添加
public Email(){}
or use existing或使用现有的
new Email("Subject","Content")
For printing then you need to override and call method e.ToString()对于打印,您需要覆盖并调用方法 e.ToString()
add method to Email class将方法添加到 Email class
public override string ToString()
{
return $"Subject-{EmailSubject} Content-{EmailContent};
}
then in foreach
然后在
foreach
Console.WriteLine(e.ToString());
Your only constructor has 2 parameters hence the error referring to Email.Email(string, string)
as you attempting to instantiate Email
with zero parameters.您唯一的构造函数有 2 个参数,因此当您尝试使用零参数实例化
Email
时,错误指的是Email.Email(string, string)
。
You should either remove the constructor from your code and use property intialisers as you already do.您应该从代码中删除构造函数并像您已经做的那样使用属性初始化器。 This works as the compiler will create a default constructor in the absence of any others.
这是因为编译器将在没有任何其他构造函数的情况下创建一个默认构造函数。
new Email() {
EmailSubject="MySubject",
EmailContent="MyContent"
}
or leave the constructor and create an instance like this.或者离开构造函数并创建一个这样的实例。
new Email("MySubject", "MyContent"}
Pick one, it makes little difference.选一个,差别不大。
You can remove that constructor with two arguments and do this object initialization.您可以使用两个 arguments 删除该构造函数并执行此 object 初始化。
List<Email> Emails = new List<Email>();
Emails.Add(new Emails{ EmailSubject = "Something", EmailContent = "Also Something"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.