Assigning values to object properties
Is there a quicker way to do the following? Want to cut down the number of lines of开发者_JAVA技巧 code.
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;
Thanks..
You could use object initializers:
var item = new SpecialObject
{
Id = 1,
Name = "name",
Dictionary = new Dictionary<string, object>{
{
{"key1", "value1"},
{"key2", "value2"}
}
}
Edit re comments:
Or use a constructor, but i think this is less readable:
calling code:
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;
}
If you can change SpecialObject
, you could (instead of Andrews solution, which may be better):
- introduce a factory
- introduce a builder
- use the constructor
For simple objects like that, i'd go like this:
var item = new SpecialObject(1, "name", new Dictionary<string, object>());
item.Dictionary.Add("key1", "value1");
item.Dictionary.Add("key2", "value2");
This would be a good time to ask yourself why the dictionary does not get initialized in the constructor anyway, feels weird to pass it every time i create a new SpecialObject.
精彩评论