我想構建一個字典,其中鍵是值對象的屬性。不過,我想在字典的add方法中構造value對象。有沒有辦法做到這一點,而不使用中間變量?將元素添加到字典中,其中鍵的屬性值爲
例如,我想要做以下事情,但當然,關鍵值在需要時不可用。
Dictionary<int,SomeComplexObject> dict = new Dicionary<int,SomeComplexObject>{
{someComplexObject.Key, new SomeComplexObject {Key = 1, Name = "FooBar"},
{someComplexObject.Key, new SomeComplexObject {Key = 2, Name = "FizzBang"}
};
我必須做這種醜陋的方式:
Dictionary<int,SomeComplexObject> dict = new Dicionary<int,SomeComplexObject>();
SomeComplexObject value1 = new SomeComplexObject{Key=1,Name = "FooBar"};
dict.Add(value1.Key,value1);
SomeComplexObject value2 = new SomeComplexObject{Key=2,Name = "FizzBang"};
dict.Add(value.Key,value2);
我不認爲這是因爲我不是關鍵專門問同樣的問題作爲 How to use an object's identity as key for Dictionary<K,V>
的字典,但是如果有一種方法可以在對象未被創建時訪問對象屬性,直到稍後在方法參數列表中。
評論[已存檔在聊天](http://chat.stackoverflow.com/rooms/136085/discussion-on-question-by-automatic-add-element-to-dictionary-where-key-is-prope) 。 –