我在我的只读属性中返回对字典的引用.如何防止消费者更改我的数据?如果这是一个IList我可以简单地返回它AsReadOnly.我能用字典做些什么吗?
Private _mydictionary As Dictionary(Of String, String)
Public ReadOnly Property MyDictionary() As Dictionary(Of String, String)
Get
Return _mydictionary
End Get
End Property
Run Code Online (Sandbox Code Playgroud) 在这一小段代码中,更改方法内的二维数组会导致更改main方法中的变量.
造成这种情况的原因是什么?如何保护main方法中的变量保持不变?
using System;
namespace example
{
class Program
{
static void Main(string[] args)
{
string[,] string_variable = new string[1, 1];
string_variable[0, 0] = "unchanged";
Console.Write("Before calling the method string variable is {0}.\n", string_variable[0,0]);
Function(string_variable);
Console.Write("Why after calling the method string variable is {0}? I want it remain unchanged.\n", string_variable[0, 0]);
Console.ReadKey();
}
private static void Function(string [,] method_var)
{
method_var[0, 0] ="changed";
Console.Write("Inside the method string variable is {0}.\n", method_var[0, 0]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后这是程序输出:
Before calling the method …Run Code Online (Sandbox Code Playgroud)