簡體   English   中英

如何在 C# 中初始化嵌套類

[英]How to initialize a nested class in C#

我正在嘗試初始化一個嵌套類,下面是嵌套類。

public class Msg
{        
    [JsonProperty("to")]
    public ToObj to { get; set; }   

    [JsonProperty("from")]
    public FromObj from { get; set; }

    [JsonProperty("timestamp")]
    public string timestamp { get; set; }

    [JsonProperty("message")]
    public MessageObj message { get; set; }
    public class ToObj
    {
        [JsonProperty("type")]
        public string type { get; set; }
        [JsonProperty("id")]
        public string id { get; set; }
        [JsonProperty("number")]
        public string number { get; set; }
    }

    public class FromObj
    {
        [JsonProperty("type")]
        public string type { get; set; }

        [JsonProperty("id")]
        public string id { get; set; }

        [JsonProperty("number")]
        public string number { get; set; }

    }        
    }

我每次都需要初始化每個類嗎? 或任何其他初始化嵌套類的方法。 請告訴我

這可以這樣做:

var foo = new Msg
{
    to = new Msg.ToObj
    {
        type = "hello",
        id = "42",
        number = "69"
    },
    from = new Msg.FromObj
    {
        type = "World",
        id = "12",
        number = "7"
    }
    // other initializations...
};

但是,我不知道您為什么使用public嵌套類。 使用分離的類會更合適。 另外, FromTo似乎共享完全相同的屬性。 它們可能是一個獨特的類:

public class Obj
{
    public string type { get; set; }
    public string id { get; set; }
    public string number { get; set; }
}

public class Msg
{        
    public Obj to { get; set; }   

    public Obj from { get; set; }

    public string timestamp { get; set; } 
}

和初始化:

var foo = new Msg
{
    to = new Obj
    {
        type = "hello",
        id = "42",
        number = "69"
    },

    from = new Obj
    {
        type = "World",
        id = "12",
        number = "7"
    }
    // other initializations...
};

嵌套類的行為與其他類一樣。 如果你想初始化它,你可以在它的構造函數上進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM