有更快的方法来做以下事情吗?想要减少代码行数.
var item = new SpecialObject();
var dictionary = new Dictionary<string, object>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
item.Name = "name";
item.Id = 1;
item.Dictionary = dictionary;
Run Code Online (Sandbox Code Playgroud)
谢谢..
And*_*ock 11
您可以使用对象初始值设定项:
var item = new SpecialObject
{
Id = 1,
Name = "name",
Dictionary = new Dictionary<string, object>{
{
{"key1", "value1"},
{"key2", "value2"}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑重新评论:
或者使用构造函数,但我认为这不太可读:
调用代码:
var item = new SpecialObject(1, "name", new Dictionary<string, object>{
{"key1", "value1"},
{"key2", "value2"}
});
Run Code Online (Sandbox Code Playgroud)
构造函数:
public SpecialObject(int id, string name, IDictionary<string, object> dict)
{
this.Id = id;
this.name = Name;
this.Dictionary = dict;
}
Run Code Online (Sandbox Code Playgroud)