質問

私は非常にシンプルなコード(元のコードから簡素化された - それが非常に賢いコードではないことを知っている)を持っています。これは、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) 'を検証します。

なぜこの警告を受け取るのか、どうしてそれを抑制せずに解決できるのか理解できませんか?できる new 戻る null?これはVisual Studio 2010のバグですか?

アップデート

私はオープンすることにしました Microsoft Connectのバグレポート.

役に立ちましたか?

解決

これをVisual Studio 2010 Premiumで、正確に指定されたものとまったくのように複製しました。 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