我在代码中遇到了一个错误,只有在启用优化的情况下构建代码时才会重现该错误。我制作了一个控制台应用程序,它复制了测试逻辑(下面的代码)。您会看到,启用优化后,执行此无效逻辑后,“值”变为空:
if ((value == null || value == new string[0]) == false)
修复很简单,并在有问题的代码下方注释掉。但是......我更担心我可能在汇编程序中遇到了一个错误,或者其他人可能解释了为什么 value 设置为 null。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace memory_testing
{
class Program
{
sta tic void Main(string[] args)
{
while(true)
{
Console.Write("Press any key to start...");
Console.ReadKey();
Console.WriteLine();
PrintManagerUser c = new PrintManagerUser();
c.MyProperty = new string[1];
}
}
}
public class PrintManager
{
public void Print(string key, object value)
{
Console.WriteLine("Key is: " + key);
Console.WriteLine("Value is: " + value);
}
}
public class PrintManagerUser
{
public string[] MyProperty
{
get { return new string[100]; }
set
{
Console.WriteLine("Pre-check Value is: " + value);
if ((value == null || value == new string[0]) == false)
{
Console.WriteLine("Post-check Value is: " + value);
new PrintManager().Print("blah", value);
}
//if (value != null && value.Length > 0)
//{
// new PrintManager().Print("blah", value);
//}
}
}
}
}
正常输出应该是:
Pre-check Value is: System.String[]
Post-check Value is: System.String[]
Key is: blah
Value is: System.String[]
错误的输出是:
Pre-check Value is: System.String[]
Post-check Value is:
Key is: blah
Value is:
我的 Env 是一个运行带有 .NET 3.5 SP1 的 Windows Server 2003 R2 的 VM。使用VS2008团队系统。
谢谢,
布赖恩