动态获取本地化字符串 WP8 c#

7

我该如何在Windows Phone 8中动态获取本地化文本? 我发现,如果我想要一个文本,我可以通过以下方式完成:

AppResources.ERR_VERSION_NOT_SUPPORTED

但是假设我从服务器获取关键词,那么我只会得到字符串的返回值。
ERR_VERSION_NOT_SUPPORTED

现在我想从AppResources获取适当的文本。
我尝试了以下方法:
string methodName = "ERR_VERSION_NOT_SUPPORTED";
AppResources res = new AppResources();
//Get the method information using the method info class
MethodInfo mi = res.GetType().GetMethod(methodName);

//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
string message = (string)mi.Invoke(res, null);

问题在于此示例中的MethodInfo mi为空... 有人有什么想法吗?
编辑: 感谢大家快速回复。 事实上,我对C#还很陌生,总是因为getter和setter语法混淆Properties。 我的AppResources看起来像这样:
/// <summary>
///   A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class AppResources
{

    ...

    /// <summary>
    ///   Looks up a localized string similar to This version is not supported anymore. Please update to the new version..
    /// </summary>
    public static string ERR_VERSION_NOT_SUPPORTED
    {
        get
        {
            return ResourceManager.GetString("ERR_VERSION_NOT_SUPPORTED", resourceCulture);
        }
    }
}

尝试动态获取属性最终未能成功...我发现我可以直接使用以下方法:

string message = AppResources.ResourceManager.GetString("ERR_VERSION_NOT_SUPPORTED", AppResources.Culture);

向大家致意


你确定 ERR_VERSION_NOT_SUPPORTED 是一个方法吗? - polkduran
2个回答

15
您无需使用反射即可访问资源。请尝试以下方法:
AppResources.ResourceManager.GetString("ERR_VERSION_NOT_SUPPORTED", 
      AppResources.Culture);

是的,谢谢!我刚刚也发现了这个问题 :) 请查看我的编辑... 非常感谢你! - schurtertom

0
首先,AppResources.ERR_VERSION_NOT_SUPPORTED不是一个方法,而是一个静态属性或静态字段。因此,你需要“搜索”静态属性(或字段)。以下是属性的示例:
string name= "ERR_VERSION_NOT_SUPPORTED";
var prop = typeof(Program).GetProperty(name, BindingFlags.Static);
string message = p.GetValue(null, null);

谢谢Garath的建议!我尝试了,但是那个变量prop仍然为空。但无论如何,最终我找到了解决方案... - schurtertom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接