最適化を有効にしてコードをビルドした場合にのみ再現されるコードのバグに遭遇しました。テスト用のロジックを複製するコンソールアプリを作成しました(以下のコード)。最適化を有効にすると、この無効なロジックの実行後に「value」がnullになることがわかります。
if ((value == null || value == new string[0]) == false)
修正は簡単で、問題のあるコードの下にコメントアウトされています。しかし...私はアセンブラのバグに遭遇したかもしれないか、おそらく他の誰かが値が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:
My Envは、.NET3.5SP1を搭載したWindowsServer2003R2を実行しているVMです。VS2008チームシステムの使用。
ありがとう、
ブライアン