こんにちは!C#コンパイラが最適化をどのように実行するかについて少し混乱しています。
「怠惰な」初期化とnullの場合のデフォルト値を構成するために次のゲッターを作成しました。
静的クラスヘルパー:
private static string host;
public static string Host
{
get
{
return host ?? (host= (ConfigurationManager.AppSettings["Host"] ?? "host.ru"));
}
}
リフレクターによる分解の結果は次のとおりです。
public static string Host
{
get
{
if (Helper.host == null)
{
string host = Helper.host;
}
return (Helper.host = ConfigurationManager.AppSettings["Host"] ?? "host.ru");
}
}
想定以外の方法で動作するようです...
アップデート
private static string host;
public static string Host
{
get
{
return host ?? (host = (GetVal() ?? "default"));
}
}
static void Main(string[] args)
{
Console.WriteLine(Host);
host = "overwritten";
Console.WriteLine(Host);
}
static string GetVal()
{
return "From config";
}
正しく動作します(構成から、上書きされます)が、Reflectorは同じことを示します:
public static string Host
{
get
{
if (Program.host == null)
{
string host = Program.host;
}
return (Program.host = GetVal() ?? "default");
}
}