全部,为了提供用于调试不同语言的应用程序的动态机制,我使用所需的资源字符串(使用外语)在用户需要时在运行时显示英语等效项。这是使用
完成的public static string GetMessage(string messageKey)
{
CultureInfo culture = Thread.CurrentThread.CurrentCulture;
if (!culture.DisplayName.Contains("English"))
{
string fileName = "MessageStrings.resx";
string appDir = Path.GetDirectoryName(Application.ExecutablePath);
fileName = Path.Combine(appDir, fileName);
if (File.Exists(fileName))
{
// Get the English error message.
using (ResXResourceReader resxReader = new ResXResourceReader(fileName))
{
foreach (DictionaryEntry e in resxReader)
if (e.Key.ToString().CompareNoCase(messageKey) == 0)
return e.Value.ToString();
}
}
}
return null;
}
GetName
定义为
public static string GetName<T>(Expression<Func<T>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
我通常在我的应用程序中显示本地化消息,如
Utils.ErrMsg(MessageStrings.SomeMessage);
或
Utils.ErrMsg(String.Format(MessageStrings.SomeMessage, param1, param2));
现在,我可以使用
显示我在不同文化中运行的应用中的相关英文消息Utils.ErrMsg(Utils.GetMessage(
Utils.GetName(() => MessageStrings.ErrCellAllocStatZeroTotal)) ??
MessageStrings.ErrCellAllocStatZeroTotal);
我想避免在调用GetName
时使用lambda表达式以及使用null
中的GetMessage
并使用??
,我该如何实现这一点[如果可能的话]?
感谢您的时间。
答案 0 :(得分:1)
我不完全理解您的代码,但如果您只想动态访问对象的属性,请尝试此操作(您必须将[Object]和“PropertyName”替换为您的特定值):
// get the property from object
PropertyInfo Property = [Object].GetType().GetProperty("PropertyName");
// get the value
int value = (int)Property.GetValue([Object], null);