bri*_*ner 8 c# code-analysis fxcop visual-studio-2010 ca1062
我有一个非常简单的代码(从原始代码中简化 - 所以我知道它不是一个非常聪明的代码),当我使用代码分析在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的警告:
CA1062:Microsoft.Design:在外部可见方法'Foo.Bar(out int [])'中,验证在使用之前从参数'x'重新分配的局部变量'(*x)'.
我不明白为什么我会收到这个警告,如何在不压制它的情况下解决它?可以new回来null吗?这是Visual Studio 2010的错误吗?
UPDATE
我决定打开关于Microsoft Connect的错误报告.
我已经在Visual Studio 2010 Premium中使用完全相同的代码并在分析设置中启用了Microsoft All Rules来复制它.
看起来这是一个错误(见这里的底部:http://msdn.microsoft.com/en-us/library/ms182182.aspx).我们抱怨你x在使用它之前没有检查它是否为null,但它是on 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
而正确的方法是:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5717 次 |
| 最近记录: |