【发布时间】:2015-12-23 09:04:39
【问题描述】:
在其中一个应用程序中,我遇到了与代码优化相关的错误。
我尝试在测试应用程序中重复此行为。该应用程序在 GitHub 上可用:https://github.com/altk/NullableError
该错误仅在您使用 .NET Native 编译时发生,但并非在所有地方都发生。错误在少数 PC 上重现。
应用程序代码非常简单。它必须打印到控制台:
-------------- 否则 --------------
-------------- 成功 --------------
但是由于它打印的优化:
-------------- 否则 --------------
-------------- 失败 --------------
应用的所有代码:
#define DEBUG
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace NullableError
{
sealed partial class App
{
private readonly Dictionary<String, String> _dictionary = new Dictionary<String, String>();
public App()
{
InitializeComponent();
Execute();
Exit();
}
private Int64? NullableInt64
{
get
{
var resultString = this[nameof(NullableInt64)];
return String.IsNullOrEmpty(resultString) ? default(Int64?) : Int64.Parse(resultString);
}
//-----FIX VARIANT------
//UNCOMMENT NEXT LINE TO FIX
//[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)]
set
{
//-----FIX VARIANT------
//REPLACE WITH
//this[nameof(NullableInt64)] = value != null ? value.Value.ToString() : null;
this[nameof(NullableInt64)] = value?.ToString();
}
}
private Int64? AnotherNullableInt64
{
get
{
var resultString = this[nameof(AnotherNullableInt64)];
return String.IsNullOrEmpty(resultString) ? default(Int64?) : Int64.Parse(resultString);
}
set { this[nameof(AnotherNullableInt64)] = value?.ToString(); }
}
private void Execute()
{
//-----FIX VARIANT------
//REPLACE WITH IF-ELSE WITH
//NullableInt64 = (DateTimeOffset.Now - DateTimeOffset.MinValue).TotalMilliseconds < 0 ? (Int64?) 125 : null;
if ((DateTimeOffset.Now - DateTimeOffset.MinValue).TotalMilliseconds < 0)
{
Debug.WriteLine("-------------- IF --------------");
NullableInt64 = 125;
}
else
{
Debug.WriteLine("-------------- ELSE --------------");
NullableInt64 = null;
}
//-----FIX VARIANT------
//REPLACE WITH
//AnotherNullableInt64 = 0;
AnotherNullableInt64 = null;
Debug.WriteLine(String.Format("-------------- {0} --------------", this[nameof(NullableInt64)] == "0" ? "FAIL" : "SUCCESS"));
}
private String this[String key]
{
get
{
String result;
return _dictionary.TryGetValue(key, out result) ? result : null;
}
set { _dictionary[key] = value; }
}
}
}
【问题讨论】:
-
请在问题中包含相关代码 - 只需输出行和相关的控制语句即可。
-
不是整个代码只是用任何相关定义证明错误的行。
-
@ChrisF:我怀疑代码已经尽可能少,同时仍然可以重现。
-
什么优化?调试打印?这是问题的一部分吗?
-
@ChrisF 代码很小。如果我只留下 Execute() 方法,没有人会理解问题。
标签: c# windows-runtime .net-native