相关疑难解决方法(0)

.NET中是否有只读通用字典?

我在我的只读属性中返回对字典的引用.如何防止消费者更改我的数据?如果这是一个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)

.net dictionary readonly

185
推荐指数
6
解决办法
7万
查看次数

方法将变量更改为其范围

在这一小段代码中,更改方法内的二维数组会导致更改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)

c# arrays multidimensional-array

0
推荐指数
1
解决办法
663
查看次数

标签 统计

.net ×1

arrays ×1

c# ×1

dictionary ×1

multidimensional-array ×1

readonly ×1