如何覆盖Resources.Designer.cs中的默认System.Resources.ResourceManager?

时间:2011-12-01 07:46:56

标签: c# asp.net resources

我想从System.Resources.ResourceManager文件覆盖Resources.Designer.cs以实现自定义ResourceManager.GetString(...)方法功能。这可能吗?

2 个答案:

答案 0 :(得分:3)

我创建了一个CustomResourceManager来覆盖GetString()调用,如下所示:

public class CustomResourceManager : ResourceManager
{
    public CustomResourceManager(Type resourceSource)
        :base(resourceSource)
    {
    }

    public CustomResourceManager(string baseName, Assembly assembly)
        : base(baseName, assembly)
    {
    }

    public CustomResourceManager(string baseName, Assembly assembly, Type usingResourceSet)
        : base(baseName, assembly, usingResourceSet)
    {
    }

    public override string GetString(string name)
    {
        // your business logic
    }

    public override string GetString(string name, CultureInfo culture)
    {
        // your business logic
    }
}

然后我在我的项目中添加了一个预构建步骤,用生成的System.Resources.ResourceManager文件中的CustomResourceManager替换Resource.Designer.cs的创建:

powershell -command "(gc ..\Resources\Resource.Designer.cs).Replace(\"new global::System.Resources.ResourceManager\", \"new CustomResourceManager\") | set-content ..\Resources\Resource.Designer.cs -Encoding UTF8"

我们离开了!

答案 1 :(得分:2)

我相信你在这里提出两个不同的问题。你当然可以覆盖ResourceManager.GetString。但是,您不能在自动生成的Resource.Designer.cs代码中使用该覆盖。要使用它,您必须编写自己的Resource设计器类。

public class MyResourceManager : System.Resources.ResourceManager
  {
    // override
    public override GetString(string name)
      {
        // custom code 
      }
  }

 public class MyResourceDesigner
   {
      // use your custom class with override
      private static MyResourceManager resourceManager;
      private static CultureInfo resourceCulture;

      public static MyResourceManager ResourceManager
         {
            if (object.ReferenceEquals(resourceManager, null))
               {
                  // Resource is just the name of the .resx file
                  // be sure to include relevant namespaces
                  var temp = new MyResourceManager(
                     "MyProject.Resource", 
                     typeof(MyResourceDesigner).Assembly);
                  resourceManager = temp;
               }

            return resourceManager;
         }

      public static CultureInfo Culture
      {
         get
         {
            return resourceCulture;
         }

         set
         {
            resourceCulture = value;
         }
      }

      // start adding strongly-typed objects
      public static string Foo
      {
         get
         {
            // use your override
            return ResourceManager.GetString("Foo", resourceCulture);
         }
      }
  }