开发者

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

开发者 https://www.devze.com 2023-03-12 20:43 出处:网络
I have this class public class TextFiller { public HtmlText Text { get; set; } publ开发者_如何学Pythonic string Details { get; set; }

I have this class

public class TextFiller
{
    public HtmlText Text { get; set; }
    publ开发者_如何学Pythonic 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消