Why do I get Code Analysis CA1062 on an out parameter in this code?

后端 未结 2 1688
别那么骄傲
别那么骄傲 2021-02-14 09:24

I have a very simple code (simplified from the original code - so I know it\'s not a very clever code) that when I compile in Visual Studio 2010 with Code Analysis gives me warn

2条回答
  •  醉话见心
    2021-02-14 09:57

    It's easier to show than to describe :

    public class Program
    {
        protected static int[] testIntArray;
    
        protected static void Bar(out int[] x)
        {
            x = new int[100];
            for (int i = 0; i != 100; ++i)
            {
                Thread.Sleep(5);
                x[i] = 1; // NullReferenceException
            }
        }
    
        protected static void Work()
        {
            Bar(out testIntArray);
        }
    
        static void Main(string[] args)
        {
            var t1 = new Thread(Work);
            t1.Start();
    
            while (t1.ThreadState == ThreadState.Running)
            {
                testIntArray = null;
            }
        }
    }
    

    And the correct way is :

        protected static void Bar(out int[] x)
        {
            var y = new int[100];
    
            for (int i = 0; i != 100; ++i)
            {
                Thread.Sleep(5);
                y[i] = 1;
            }
    
            x = y;
        }
    

提交回复
热议问题