Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

C# Create an object and add to a list

I have a basic csharp objects question. I want to add my emails to a list and display their content.

I have created my 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.

    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

What am i doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you are trying to call parameterless constructor in new new Email() and its not specified

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()

add method to Email class

public override string ToString()
{
     return $"Subject-{EmailSubject} Content-{EmailContent};
}

then in foreach

Console.WriteLine(e.ToString());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...