加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 调试时静态变量初始化程序的运行时评估中的奇数

发布时间:2020-12-15 21:33:31 所属栏目:百科 来源:网络整理
导读:当我从Visual Studio内部启动它时,我的应用程序运行正常,附带调试器(F5).但是当我在没有附加调试器(Ctrl-F5或启动.exe文件)的情况下启动应用程序时,我总是得到一个StackOverflowException,幸运地记录在 Windows事件日志中. 有问题的代码如下: namespace Cal
当我从Visual Studio内部启动它时,我的应用程序运行正常,附带调试器(F5).但是当我在没有附加调试器(Ctrl-F5或启动.exe文件)的情况下启动应用程序时,我总是得到一个StackOverflowException,幸运地记录在 Windows事件日志中.

有问题的代码如下:

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?

当没有静态构造函数时,静态变量初始值设定项的行为很少得到保证.实际上,您甚至可以在不调用静态变量初始化程序的情况下创建类的实例!当您使用调试器时,CLR会以不同的方式执行各种操作(尤其是围绕JITting).

使用静态构造函数可能是为您提供更可预测的初始化行为的最佳方法.

有关更多信息,请参阅我的blog post about type initialization changes in .NET 4.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读