是否可以创建两个文件,例如
Text.Debug.resx
和Text.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($"StackOverflow.Text.{configuration}", typeof(Resources).Assembly);
}
public string GetString(string resourceKey)
{
return _resourceManager.GetString(resourceKey);
}
}
显然,在更新管理器时适当修改命名空间。
您还可以将其实现为静态类,以避免必须新建包装器的实例:
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($"StackOverflow.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
{
}
}