有更快的方法来执行以下操作吗?想要减少代码行数。
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;
谢谢..
最佳答案
您可以使用对象初始化程序:
var item = new SpecialObject
{
Id = 1,
Name = "name",
Dictionary = new Dictionary<string, object>{
{
{"key1", "value1"},
{"key2", "value2"}
}
}
编辑评论:
或使用构造函数,但我认为这不太可读:
调用代码:
var item = new SpecialObject(1, "name", new Dictionary<string, object>{
{"key1", "value1"},
{"key2", "value2"}
});
ctor:
public SpecialObject(int id, string name, IDictionary<string, object> dict)
{
this.Id = id;
this.name = Name;
this.Dictionary = dict;
}
关于c# - 为对象属性分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3676080/