Does C# support the use of static local variables?

后端 未结 12 938
眼角桃花
眼角桃花 2020-12-14 17:28

Related: How do I create a static local variable in Java?


Pardon if this is a duplicate; I was pretty sure this would have been

12条回答
  •  庸人自扰
    2020-12-14 17:58

    Unfortunately, no. I really loved this possibility in C.

    I have an idea what you could do.

    Create a class that will provide access to instance-specific values, which will be preserved statically.

    Something like this:

    class MyStaticInt
    {
        // Static storage
        private static Dictionary  staticData =
            new Dictionary  ();
    
        private string InstanceId
        {
            get
            {
                StackTrace st = new StackTrace ();
                StackFrame sf = st.GetFrame (2);
                MethodBase mb = sf.GetMethod ();
    
                return mb.DeclaringType.ToString () + "." + mb.Name;
            }
        }
    
        public int StaticValue
        {
            get { return staticData[InstanceId]; }
    
            set { staticData[InstanceId] = value; }
        }
    
        public MyStaticInt (int initializationValue)
        {
            if (!staticData.ContainsKey (InstanceId))
                staticData.Add (InstanceId, initializationValue);
        }
    }
    

    Can be used this way...

    class Program
    {
        static void Main (string[] args)
        {
            // Only one static variable is possible per Namespace.Class.Method scope
            MyStaticInt localStaticInt = new MyStaticInt (0);
    
            // Working with it
            localStaticInt.StaticValue = 5;
            int test = localStaticInt.StaticValue;
        }
    }
    

    It's not a perfect solution, but an interesting toy.

    You can only have one static variable of this type per Namespace.Class.Method scope. Won't work in property methods - they all resolve to the same name - get_InstanceId.

提交回复
热议问题