C# c字典指定变量的值

C# c字典指定变量的值,c#,variables,dictionary,C#,Variables,Dictionary,我在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

我在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也得到了值2:

key: 1, val1: 2, val2: 2
key: 2, val1: 2, val2: 2
看起来这个任务是通过引用而不是通过值。。。
也许你可以帮我分配类变量的实际值,而不是它的引用?

你的假设完全正确,它与引用有关。当您只是更改test_类实例的属性时,这些更改将通过对该实例的所有引用反映出来。您可以考虑创建一个新实例:

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);
或者,将参考tmp_测试重新分配给一个新实例:tmp_测试=新测试类


注意:在您的示例TestClass中,类名应该是PascalCase,您只创建test_类的一个实例,并将该实例添加到字典中两次。通过在再次将其添加到字典之前对其进行修改,也会影响已添加的实例,因为它是同一个实例,字典中只有对它的多个引用

因此,与其修改一个对象,不如创建新对象:

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_测试分配了一个新对象,因此添加到字典中的引用现在是对新对象的引用,因此它独立于我们添加到字典中的第一个对象

但是请记住,对象仍然是可变的,因此您可以很好地执行类似的操作,它将修改字典中的对象以及存在对它们的引用的任何地方:

tmp_dict[1].val1 = 123;
tmp_dict[2].val2 = 42;

祝你好运

你可以轻松一点:

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

这是因为test_类是引用类型。使用不同的变量。我认为引用是一个不幸的词语选择。tmp_test的值被复制到字典中,但该值是一个引用。这与ref参数的by-reference不同。使用集合初始值设定项时更好:var tmp_dict=new Dictionary{{1,new test_class{val1=1,val2=1}},{2,new test_class{val1=2,val2=2};
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);
                        }
tmp_dict.Add(1, new test_class{val1 = 1, val2 = 1;});
tmp_dict.Add(2, new test_class{val1 = 2, val2 = 2;});