2013-08-07 44 views
0

全部,提供用於以不同語言調試應用程序的即時機制我使用所需的資源字符串(使用外語)來顯示如果用戶需要,在運行時英文相當。這是使用如何使用在運行時獲得的變量名稱

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)); 

現在我可以做DISP躺在離我的應用程序在不同的文化運行使用

Utils.ErrMsg(Utils.GetMessage(
    Utils.GetName(() => MessageStrings.ErrCellAllocStatZeroTotal)) ?? 
     MessageStrings.ErrCellAllocStatZeroTotal);  

我想,以避免在調用GetName和使用??GetMessage和使用null使用lambda表達式培訓相關英文消息,我怎麼能實現這個[如果可能的話]?

謝謝你的時間。

+0

你怎麼不只是從'Utils.GetMessage'返回'messageKey'(它的原始值,而不是'GetName'的返回值的覆蓋版本)而不是''。我一定在這裏錯過了一些東西,所以請賜教:) –

+0

我不得不編輯這個問題,因爲我略微領先於自己。我可以像我在做的那樣傳遞'MessageString'實例,或者反射返回'GetMessage'中的局部變量名稱。我現在有兩個問題 - 避免調用lambda,不必使用null合併操作符!謝謝你的時間。 – MoonKnight

回答

1

我不完全理解你的代碼,但如果你只是想動態訪問對象的屬性,試試這個(你要替換[對象]和「屬性名」使用特定的值):

// get the property from object 
PropertyInfo Property = [Object].GetType().GetProperty("PropertyName"); 

// get the value 
int value = (int)Property.GetValue([Object], null);