How to use a localized string inside a static method
-
21-12-2019 - |
Pergunta
I have to use a translated string into a static method, but it doesn't let me use the keyword 'this'.
My code is something like the following:
public static async Task<string> UtilityMethod(){
[...]
this.resourceLoader.GetString("LocalizedString")
[...]
}
How can I do?
Solução
Well, you can't use non-static properties (or fields) in a static method.
As a workaround you can make your resourceLoader also static, or modify the UtilityMethod to have a parameter, so to give you code:
private static readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources");
Or:
public static async Task<string> UtilityMethod(ResourceLoader resourceLoader){
[...]
resourceLoader.GetString("LocalizedString")
[...]
}
Outras dicas
First of all this keyword is not allowed to be used in the static method.
Reason behind is when you make the method static the method is nomore visible to the instance created of the Class.
public class DemoClass
{
public int value1 {get;set;}
public int value2 {get;set;}
//if you see the below I am using this
public void method1()
{
Console.Write(string.Format("value1: {0} value2: {1}", this.value1, this.value1));
}
public static void method2()
{
//I callnot access my properties it self :(
//and cannot be accesed
}
Useing the extension method to the string class or by overriding the toString() method to translate the string
Extension Methods http://msdn.microsoft.com/en-us//library/bb383977.aspx
Override the ToString http://msdn.microsoft.com/en-IN/library/ms173154(v=vs.80).aspx