C#预处理器指令(#if和#endif)不起作用。编译错误

时间:2015-08-27 14:16:05

标签: c# c#-4.0 c-preprocessor

我正在尝试调试VS2010,4.0框架中的现有应用程序。我得到这个编译时错误:

  

“当前上下文中不存在名称'b_resources'”。

我在下面的代码中看不到任何错误:

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;

#if TR
    using b_resources = Common.Resources.TResources;
#endif

#if EN
    using b_resources = Common.Resources.EnResources;
#endif

namespace Common
{
    public static class BResources
    {

        public static string caption { get { return b_resources.ProductName; } }
        public static string company_name { get { return b_resources.CompanyName; } }
    }
}

TResourcesEnResources是资源文件(.resx)

我错过了一些与.Net相关的参考资料吗?

3 个答案:

答案 0 :(得分:2)

最明显的问题是:您是否在当前版本中定义了TREN编译符号?如果不是,则两个#IF语句都将为false,并且不会包含using语句。换句话说,如果您没有定义这些符号,则将编译以下代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;

// Note: missing using statements

namespace Common
{
    public static class BResources
    {

        public static string caption { get { return b_resources.ProductName; } }
        public static string company_name{ get { return b_resources.CompanyName; } }
    }
}

要检查或设置编辑符号,请转到项目的属性。然后在“构建”选项卡上,您将看到名为“条件编译符号”的文本框。检查符号是否在那里定义。如果没有,请在其中添加其中一个。

如果您使用的是Visual Studio,事实上您可以立即查看是否是这种情况。如果没有为当前构建定义符号,则#IF块中的代码将显示为灰色。如果定义了符号,它将像普通代码一样显示jsut。

答案 1 :(得分:1)

您没有默认情况,因此如果未定义TR或EN,则不会定义b_resources。你需要在那里有一些其他情况,所以它总是可以编译。例如,如果您希望将EN资源作为默认值:

#if TR
    using b_resources = Common.Resources.TResources;
#elif EN
    using b_resources = Common.Resources.EnResources;
#else
    using b_resources = Common.Resources.EnResources; // or whatever you want as default
#endif

如果既未定义TR或EN,也会包含最终的其他内容。

答案 2 :(得分:0)

要编译代码,需要在Project属性的Build设置中定义TR或EN。目前都没有定义,所以b_resources永远不会被定义。