c# - 如何在 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
嵌套类。使用单独的类会更合适。另外,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...
};
推荐阅读
- python-3.x - 使用 Mongoengine 对文档中的两个键进行求和或差运算
- react-native - 反应原生字体大小不缩放
- swift - 我无法解决它。线程 1:致命错误:在展开可选值时意外发现 nil
- haskell - 返回多个单子
- html - Angular 6 Forms TypeError:无法读取null的属性“有效”
- python - 代码在“退出”或“退出”后仍然执行,Python,Spyder
- c++ - 如何在 if-else 语句中使用 C++20 的可能/不太可能属性
- jquery - 如何限制选择列表 - 在 KnockoutJS 中只选择一项
- python-2.7 - 想在给出答案后终止程序
- android - 根据preference change listener改变android view model的查询参数