如何使用在运行时获得的变量名称
本文关键字:变量名 何使用 运行时 | 更新日期: 2023-09-27 18:26:41
All,为了提供用不同语言调试应用程序的即时机制,如果用户需要,我将使用所需的资源字符串(外语)在运行时显示等效的英语。这是使用完成的
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表达式,以及从GetMessage
使用null
和使用??
,我如何实现这一点(如果可能的话)?
谢谢你抽出时间。
我不完全理解您的代码,但如果您只想动态访问对象的属性,请尝试以下操作(您必须用特定值替换[object]和"PropertyName"):
// get the property from object
PropertyInfo Property = [Object].GetType().GetProperty("PropertyName");
// get the value
int value = (int)Property.GetValue([Object], null);