Getting a string dynamically from strings resources

前端 未结 5 2145
鱼传尺愫
鱼传尺愫 2020-12-09 08:11

I am working on a localised C#.NET application and we are using a strings.resx file to translate hardcoded strings in the application. I use the following code

相关标签:
5条回答
  • 2020-12-09 08:22

    There is much simpler way of doing this

     [NameOfyourResxfile].ResourceManager.GetString("String Name");
    

    in your case

    strings.resx.ResourceManager.GetString("someString");
    
    0 讨论(0)
  • 2020-12-09 08:25

    I had the same problem using ASP.NET Core MVC and managed to solve it using

    ResourceManager rm = new ResourceManager(typeof(YourResourceClass));
    string someString = rm.GetString("someString");
    

    Very similar to @Vlad's solution, but otherwise I had a MissingManifestResourceException

    0 讨论(0)
  • 2020-12-09 08:34

    You can write a static method like this:

    public static string GetResourceTitle<T>(string key)
    {
      ResourceManager rm = new ResourceManager(typeof(T));
      string someString = rm.GetString(key);
      return someString;
    }
    

    And call anywhere:

    var title=  GetResourceTitle<*YouResourceClass*>(key);
    

    It is useful when you want to have a generic function to get String of any Resource file.

    0 讨论(0)
  • 2020-12-09 08:38

    A little searching did the trick. I have the right ResourceManager available in my strings class:

    ResourceManager rm = strings.ResourceManager;
    string someString = rm.GetString("someString");
    
    0 讨论(0)
  • 2020-12-09 08:45

    ResourceManager.GetString should do.

    Stripped down example from MSDN:

    ResourceManager rm = new ResourceManager("RootResourceName",
                                             typeof(SomeClass).Assembly);
    string someString = rm.GetString("someString");
    
    0 讨论(0)
提交回复
热议问题