简体   繁体   中英

Static Dictionary fields used to implement static method

Inside a class I have some properties, two static Dictionaries (private fields) a one static method. The method initializes the properties querying the dictionaries and after a switch returns a string. For some reason the values is always returned as null. Below a simplified version:

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) for example returns, correctly, the string "EMPTY" but from 1 to 3 return null. I'm missing something? Is there any more correct/clean way to do the same thing? Thanks!

The method initializes the properties querying the dictionaries and after a switch returns a string.

Yes, when the method is called, the properties will be initialized. Happens after the Encoding dictionary is populated though. The Encoding dictionary is populated as soon as the type is initialized, and at that point, all the properties will have a value of null.

It's not at all clear to me what you're attempting to achieve here, but I would strongly recommend redesigning the code to avoid this confusion.

(I'd also generally warn against having static mutable properties, and I'd at least suggest using regular .NET naming conventions for them.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM