简体   繁体   中英

How can I pre-populate a simple class with data?

I have this class

public class TextFiller
{
    public HtmlText Text { get; set; }
    public string Details { get; set; }
}

public class HtmlText { 
    [AllowHtml]
    public string TextWithHtml { get; set; } 
}

How can I change the class so that when I do the following it creates a TextFiller instance with TEXT populated with "" and Details populated with ""?

I assume constructors but I am still learning and would appreciate help. In particular I am confused because I suppose I need to have a constructor for HtmlText also.

As you've already guessed, you can set the initial values of properties from within a constructor:

public class TextFiller
{
    public TestFiller()
    {
        Text = new HtmlText();
        Details = "";
    }

    public HtmlText Text { get; set; }
    public string Details { get; set; }
}

public class HtmlText
{ 
    public HtmlText()
    {
        TextWithHtml = "";
    }

    [AllowHtml]
    public string TextWithHtml { get; set; } 
}

See also: Constructors (C# Programming Guide)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM