Does C# support the use of static local variables?

后端 未结 12 896
眼角桃花
眼角桃花 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:52

    Nesting the related members in an inner class as you have shown in question is the cleanest most probably. You need not push your parent method into inner class if the static variable can somehow get the caller info.

    public class MyClass 
    {
        ...
        class Helper
        {
            static Regex re = new Regex("\\(copy (\\d+)\\)$");
            string caller;
    
            internal Helper([CallerMemberName] string caller = null)
            {
                this.caller = caller;
            }
    
            internal Regex Re
            {
                //can avoid hard coding
                get
                {
                    return caller == "AppendCopyToFileName" ? re : null;
                }
                set
                {
                    if (caller == "AppendCopyToFileName")
                        re = value;
                }
            }
        }
    
    
        private static string AppendCopyToFileName(string f)
        {
            var re = new Helper().Re; //get
            new Helper().Re = ...; //set
        }
    
    
        private static void Foo() 
        {
            var re = new Helper().Re; //gets null
            new Helper().Re = ...; //set makes no difference
        }
    }
    
    1. You can avoid hard coding of method names in the property using some expression tree tricks.

    2. You can avoid the helper constructor and make the property static, but you need to get the caller info inside the property, via using StackTrace.

    Lastly, there is always const possible inside a method, but then one, it's not variable, two, only compile time constants are allowed. Just stating.

提交回复
热议问题