在其中一个应用程序中,我遇到了与代码优化相关的错误.
我试图在测试应用程序中重复此行为.该应用程序可在GitHub上获得:https://github.com/altk/NullableError
只有在使用.NET Native进行编译时才会发生错误,但不是在任少数PC上出现错误.
应用程序代码非常简单.它必须打印到控制台:
————– ELSE ————–
————–成功————–
但由于优化它打印:
————– ELSE ————–
————–失败————–
该应用程序的所有代码:
#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; } } } }
解决方法
微软证实了这个错误.
https://connect.microsoft.com/VisualStudio/feedback/details/2164313/net-native-optimization-breaks-an-application#
https://connect.microsoft.com/VisualStudio/feedback/details/2164313/net-native-optimization-breaks-an-application#
它将在即将推出的VS 2015 Update 2中修复
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。