有问题的代码如下:
namespace Caliburn.Micro.Contrib { public static class FrameworkExtensions { public static class ViewLocator { static readonly Func<string,object,IEnumerable<string>> _baseTransformName = Micro.ViewLocator.TransformName; public static void EnableContextFallback() { Caliburn.Micro.ViewLocator.TransformName = FallbackNameTransform; } static IEnumerable<string> FallbackNameTransform(string typeName,object context) { var names = _baseTransformName(typeName,context); if (context != null) { names = names.Union(_baseTransformName(typeName,null)); } return names; } } } }
我在App启动期间调用了FrameworkExtensions.EnableContextFallack()方法,并在第一次调用Caliburn.Micro.ViewLocator.TransformName期间发生了StackOverflowException.这意味着在没有附加调试器时以及在附加调试器时调用EnableContextFallback()之前调用EnableContextFallback()之后初始化_baseTransformName变量.
namespace Caliburn.Micro.Contrib { public static class FrameworkExtensions { public static class ViewLocator { static readonly Func<string,IEnumerable<string>> _baseTransformName; static ViewLocator() { _baseTransformName = Micro.ViewLocator.TransformName; } public static void EnableContextFallback() { Caliburn.Micro.ViewLocator.TransformName = FallbackNameTransform; } static IEnumerable<string> FallbackNameTransform(string typeName,null)); } return names; } } } }
这可确保在第一次调用EnableContextFallback()之前始终设置变量_baseTransformName.
所以问题是:为什么在附加调试器时静态变量有不同的初始化行为,是否有办法“禁用”不同的行为?
干杯
解决方法
So the question is: Why is there a different initialization behavior for static variables when a debugger is attached and is there a way to “disable” the different behavior?
@H_404_34@当没有静态构造函数时,静态变量初始值设定项的行为很少得到保证.实际上,您甚至可以在不调用静态变量初始化程序的情况下创建类的实例!当您使用调试器时,CLR会以不同的方式执行各种操作(尤其是围绕JITting).
使用静态构造函数可能是为您提供更可预测的初始化行为的最佳方法.
有关更多信息,请参阅我的blog post about type initialization changes in .NET 4.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。