【问题标题】:How to initialize a nested class in C#如何在 C# 中初始化嵌套类
【发布时间】:2020-12-13 02:48:46
【问题描述】:

我正在尝试初始化一个嵌套类,下面是嵌套类。

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# .net oop


    【解决方案1】:

    这可以这样完成:

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

    【讨论】:

    • 感谢您的回答,我会考虑您的建议。
    【解决方案2】:

    嵌套类的行为与其他类一样。如果你想初始化它,你可以在它的构造函数上做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2016-08-08
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多