首页 > 解决方案 > 如何在 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; }

    }        
    }

我每次都需要初始化每个类吗?或任何其他方式来初始化嵌套类。请告诉我

标签: c#.netoop

解决方案


这可以这样做:

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嵌套类。使用单独的类会更合适。另外,From并且To似乎具有完全相同的属性。它们可能是一个独特的类:

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...
};

推荐阅读