2015-10-29 81 views
0

我在將變量的值賦給c#中的字典時遇到了一些麻煩。c#字典賦值變量的值

這裏是例子。我有以下類:

public class test_class 
{ 
    public int val1; 
    public int val2; 
} 

而且我運行下面的代碼:

Dictionary<int, test_class> tmp_dict = new Dictionary<int, test_class>(); 

tmp_test.val1 = 1; 
tmp_test.val2 = 1; 
tmp_dict.Add(1, tmp_test); 

tmp_test.val1 = 2; 
tmp_test.val2 = 2; 
tmp_dict.Add(2, tmp_test); 

foreach (KeyValuePair<int, test_class> dict_item in tmp_dict) 
{   
    Console.WriteLine("key: {0}, val1: {1}, val2: {2}", dict_item.Key, dict_item.Value.val1, dict_item.Value.val2); 
} 

現在,我將有望得到下面的輸出(鍵1與1的值)

key: 1, val1: 1, val2: 1 
key: 2, val1: 2, val2: 2 

,但我得到以下一(key1的也得到了值爲2):

key: 1, val1: 2, val2: 2 
key: 2, val1: 2, val2: 2 

它看起來像這個任務是通過引用,而不是通過值... 也許你可以幫助我分配類變量的實際值,而不是它的參考?

+1

這是因爲爲test_class是一個典型的參考即使用不同的變量。 –

回答

3

你的假設是絕對正確的,它與參考文獻有關。當您只是更改您的實例test_class的屬性時,這些更改將反映在對該實例的所有引用中。您可以考慮創建一個新的實例:

tmp_test = new test_class(); 
tmp_test.val1 = 1; 
tmp_test.val2 = 1; 
tmp_dict.Add(1, tmp_test); 

tmp_test1 = new test_class(); 
tmp_test1.val1 = 2; 
tmp_test1.val2 = 2; 
tmp_dict1.Add(2, tmp_test1); 

Alternativly重新分配您參考tmp_test到一個新的實例:tmp_test = new test_class()

NB:類名應該是PascalCase(你的情況TestClass

+0

我認爲「通過參考」是一個不幸的詞選擇在這裏。 'tmp_test'的值被複制到字典中,但該值*是一個引用。這與'ref'參數的「引用」不同。 –

4

你只創建test_class的一個實例,並兩次添加實例的字典。通過在再次將其添加到字典之前對其進行修改,您也會影響已添加的實例 - 因爲它是相同的實例,它們在字典中只有多個引用。

所以不是修改一個對象的,創建新的:

test_class tmp_test; 

// create a new object 
tmp_test = new test_class(); 
tmp_test.val1 = 1; 
tmp_test.val2 = 1; 
tmp_dict.Add(1, tmp_test); 

// create another new object 
tmp_test = new test_class(); 
tmp_test.val1 = 2; 
tmp_test.val2 = 2; 
tmp_dict.Add(2, tmp_test); 

由於一個新的對象被分配到tmp_test,被添加到詞典中的參考是現在參照對象,所以它與我們添加到字典中的第一個對象無關。

但要記住的是,對象仍然可變的,所以你可以做這樣的事情就好了,它會在字典中修改的對象(和其他任何地方對它們的引用存在):

tmp_dict[1].val1 = 123; 
tmp_dict[2].val2 = 42; 
0
Dictionary<int, test_class> tmp_dict = new Dictionary<int, test_class>(); 

test_class tmp_test = new test_class(); 
tmp_test.val1 = 1; 
tmp_test.val2 = 1; 
tmp_dict.Add(1, tmp_test); 

tmp_test = new test_class(); //You Need to initialize the variable again. 
tmp_test.val1 = 2; 
tmp_test.val2 = 2; 
tmp_dict.Add(2, tmp_test); 

foreach (KeyValuePair<int, test_class> dict_item in tmp_dict) 
         { 
Console.WriteLine("key: {0}, val1: {1}, val2: {2}", dict_item.Key, dict_item.Value.val1, dict_item.Value.val2); 
         } 

好運

1

你可以這樣做更容易一點:

tmp_dict.Add(1, new test_class{val1 = 1, val2 = 1;}); 
tmp_dict.Add(2, new test_class{val1 = 2, val2 = 2;}); 
+0

甚至更​​好與集合初始化:'VAR tmp_dict =新詞典 \t \t \t { \t \t \t \t {1,新爲test_class {VAL1 = 1,VAL2 = 1}}, \t \t \t \t { 2,new test_class {val1 = 2,val2 = 2}} \t \t \t};' – ASh