区域可以用作变量吗?

问题描述 投票:0回答:2

我正在代码中执行数据库清理。看起来如下:

#region Orders and SubOrders
try
{
    ... // this code tries to remove the Orders and the SubOrders
}
catch (Exception ex)
{
    _logger.Error($"An exception occurred while cleaning Orders and SubOrders. Error message=[{ex.Message}]");
}

#region Customers
try
{
    ... // this code tries to remove the Customers
}
catch (Exception ex)
{
    _logger.Error($"An exception occurred while cleaning Customers. Error message=[{ex.Message}]");
}

是否可以将

_logger
行替换为:

_logger.Error($"An exception occurred while cleaning [{#currentregion}]. Error message=[{ex.Message}]");

提前致谢

c# preprocessor region
2个回答
3
投票

不,你不能。在 C# 中,#region 指令是 C# 预处理器的一项功能,允许您在编辑器中出于组织目的对代码段进行分组,但它不具有任何运行时存在。编译代码后,#region 指令不会保留在编译后的二进制文件中


0
投票

您无法使用

#region
来执行此操作。

可能更好的设计是为当前的每个

#region
部分提供单独的方法。然后,您可以使用反射来获取要注入异常消息的方法的名称:

void RemoveOrdersAndSubOrders()
{
    try
    {
        ... // this code tries to remove the Orders and the SubOrders
    }
    catch (Exception ex)
    {
        string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
        _logger.Error($"An exception occurred in {method}. Error message=[{ex.Message}]");
    }
}

(当然,如果您在抛出异常时还记录了堆栈跟踪,那么您就已经知道了该方法的名称。)

无论如何,将长方法拆分为更小的方法调用可以说是更好的设计。

© www.soinside.com 2019 - 2024. All rights reserved.