如何创建单独的资源文件用于调试和发布?

How to create separate resource files for debugging and releasing?

是否可以创建两个文件,例如Text.Debug.resxText.Release.resx,在程序调试和发布期间自动加载相应的资源文件?

我将包装 ResourceManager:

public class Resources
{
    private readonly ResourceManager _resourceManager;

    public Resources()
    {
#if DEBUG
        const string configuration = "Debug";
#else
        const string configuration = "Release";
#endif

        _resourceManager = new ResourceManager($"Whosebug.Text.{configuration}", typeof(Resources).Assembly);
    }

    public string GetString(string resourceKey)
    {
        return _resourceManager.GetString(resourceKey);
    }
}

显然,在更新管理器时适当修改命名空间。

编辑

您也可以将其实现为静态 class 以避免必须新建包装器实例:

public static class Resources
{
    private static ResourceManager _resourceManager;

    public static string GetString(string resourceKey)
    {
        if (_resourceManager != null)
        {
            return _resourceManager.GetString(resourceKey);
        }

#if DEBUG
        const string configuration = "Debug";
#else
        const string configuration = "Release";
#endif

        _resourceManager = new ResourceManager($"Whosebug.Text.{configuration}", typeof(Resources).Assembly);

        return _resourceManager.GetString(resourceKey);
    }
}

在Properties下创建2个子目录:Debug和Release。将 Resources.resx 和 Resources.Designer.cs 文件复制到每个目录。它将使用命名空间 ProjectName.Properties.Debug 或 ProjectName.Properties.Release 重新生成 Resources.Designer.cs 文件。编辑 .csproj 文件以对这些文件设置适当的条件,如下所示:

<Compile Include="Properties\Debug\Resources.Designer.cs" Condition="$(Configuration.StartsWith('Debug')) ">
   ...

<EmbeddedResource Include="Properties\Debug\Resources.resx" Condition="$Configuration.StartsWith('Debug'))">
   ...

然后在Properties目录下添加一个Resources.cs文件,用#if DEBUG判断是继承自Properties.Debug.Resources还是Properties.Release.Resources:

namespace ProjectName.Properties
{
    class Resources
#if DEBUG
        : ProjectName.Properties.Debug.Resources
#else
        : ProjectName.Properties.Release.Resources
#endif
    {
    }
}