【问题标题】:Static Dictionary fields used to implement static method用于实现静态方法的静态字典字段
【发布时间】:2020-03-30 12:44:55
【问题描述】:

在一个类中,我有一些属性,两个静态字典(私有字段)一个静态方法。该方法初始化查询字典的属性,并在切换后返回一个字符串。由于某种原因,这些值始终返回为 null。下面是简化版:

using System;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        public static string first { get; set; }
        public static string second { get; set; }
        public static string third { get; set; }

        private static Dictionary<int, string> Symbols = new Dictionary<int, string>
        {
            [1] = "A",
            [2] = "B",
            [3] = "C"
        };
        private static Dictionary<int, string> Encoding = new Dictionary<int, string>
        {
            [1] = first,
            [2] = second,
            [3] = third
        };

        public static string Encode (int n)
        {
            string result;
            first = Symbols[1];
            second = Symbols[2];
            third = Symbols[3];

            switch (n)
            {
                case 1:
                    result = Encoding[1];
                    break;
                case 2:
                    result = Encoding[2];
                    break;
                case 3:
                    result = Encoding[3];
                    break;
                default:
                    result = "EMPTY";
                    break;
            }
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(Encode(1));
        }
    }
}

Encode(4) 例如正确返回字符串“EMPTY”,但从 1 到 3 返回 null。我错过了什么?有没有更正确/干净的方法来做同样的事情?谢谢!

【问题讨论】:

  • 您正在调用 result = Encoding[1]Encoding 类型的 Encoding 字段已使用数字索引器初始化,但它指向空值属性在初始化时我>。更改属性first 的分配不会更改字典正在使用的值,这将保持null
  • case 1: return first 会为您保存字典和错误。开关其实和字典是一回事,只是不能在运行时修改。

标签: c# oop


【解决方案1】:

该方法初始化查询字典的属性,并在切换后返回一个字符串。

是的,当调用方法时,属性将被初始化。发生之后 Encoding 字典虽然被填充。 Encoding 字典会在类型初始化后立即填充,此时所有属性的值都将为 null。

我完全不清楚您在这里试图实现什么,但我强烈建议重新设计代码以避免这种混淆。

(我通常也会警告不要使用静态可变属性,我至少建议对它们使用常规的 .NET 命名约定。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2014-05-24
    • 2011-10-18
    • 2015-02-12
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多