How to use a Variable Name which was Obtained at Run-Time
All, to provide a on-the-fly mechanism for debugging an application in
different languages I am using the required resource string (in a foreign
language) to display the English equivalent at run-time should the user
require it. This is done using
public static string GetMessage(string messageKey)
{
messageKey = Utils.GetName(() => 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;
}
Where GetName is defined as
public static string GetName<T>(Expression<Func<T>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
I usually display localised messages in my application like
Utils.ErrMsg(MessageStrings.SomeMessage);
or
Utils.ErrMsg(String.Format(MessageStrings.SomeMessage, param1, param2));
Now I can display the relevent English message from my app running in a
different culture using
Utils.ErrMsg(Utils.GetMessage(MessageStrings.SomeMessage) ??
MessageStrings.SomeMessage);
I want to avoid having to return null from GetMessage and using ??, but to
avoid this I need to, in GetMessage do
return MessageStrings.messageKey;
This is clearly not possible without some sort of reflection, but how do I
achieve this?
Thanks for your time.
No comments:
Post a Comment