【问题标题】:How to tell if calling assembly is in DEBUG mode from compiled referenced lib如何从编译的引用库中判断调用程序集是否处于调试模式
【发布时间】:2017-12-28 23:10:48
【问题描述】:

我有一个引用库,如果引用它的程序集处于调试/发布模式,我想在其中执行不同的操作。

是否可以在调用程序集处于DEBUG/RELEASE模式的情况下开启?

有没有办法做到这一点而不诉诸于:

bool debug = false;

#if DEBUG
debug = true;
#endif

referencedlib.someclass.debug = debug;

引用程序集将始终是应用程序(即 Web 应用程序)的起点。

【问题讨论】:

    标签: c#


    【解决方案1】:

    Google says 很简单。您从相关程序集的DebuggableAttribute 获取信息:

    IsAssemblyDebugBuild(Assembly.GetCallingAssembly());
    
    private bool IsAssemblyDebugBuild(Assembly assembly)
    {
        foreach (var attribute in assembly.GetCustomAttributes(false))
        {
            var debuggableAttribute = attribute as DebuggableAttribute;
            if(debuggableAttribute != null)
            {
                return debuggableAttribute.IsJITTrackingEnabled;
            }
        }
        return false;
    }
    

    【讨论】:

    • 很抱歉让您感到痛苦,但“Google”什么也没说。这是获取我的一些示例,因为我是太懒的工具。 :D
    • @Andrew:我的评论不是针对你的。只是对搜索引擎的嘲讽。 :) 干杯!
    • 如果您改用 Assembly.GetEntryAssembly(),这适用于 .NET Core(含义不同,但可能已经足够好了)。
    【解决方案2】:

    接受的答案是正确的。这是跳过迭代阶段并作为扩展方法提供的替代版本:

    public static class AssemblyExtensions
    {
        public static bool IsDebugBuild(this Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }
    
            return assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITTrackingEnabled ?? false;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用reflection 获取调用程序集并使用this method 检查它是否处于调试模式。

      【讨论】:

        猜你喜欢
        • 2017-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 2014-11-13
        • 2010-10-13
        相关资源
        最近更新 更多