我有一个非常简单的代码(从原始代码中简化了,所以我知道这不是一个非常聪明的代码),当我在Visual Studio 2010中使用代码分析编译时,请给我警告CA1062:验证公共方法的参数。

public class Foo
{
    protected static void Bar(out int[] x)
    {
        x = new int[1];
        for (int i = 0; i != 1; ++i)
            x[i] = 1;
    }
}

我得到的警告:

CA1062:Microsoft.design:在外部可见的方法“ foo.bar(out int [])'中,验证局部变量'(*x)',在使用之前从参数'x'重新分配。

我不明白为什么我会得到此警告,如何在不抑制它的情况下解决它?能 new 返回 null?这是Visual Studio 2010错误吗?

更新

我决定打开 Microsoft Connect上的错误报告.

有帮助吗?

解决方案

我已经在Visual Studio 2010中复制了这一点,并完全按照给定的代码和 Microsoft所有规则 在分析设置中启用。

看起来这是一个错误(请参阅此处的底部: http://msdn.microsoft.com/en-us/library/ms182182.aspx)。抱怨您没有检查 x 使用之前不是零,但它已经打开 out 参数,因此没有输入值可以检查!

其他提示

显示比描述要容易:

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;
        }
    }
}

正确的方法是:

    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;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top