2015-10-29 80 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