2016-04-14 58 views
3

我必須訪問我的弱資源類型的資源文件,這意味着我必須通過ResourceManager傳遞完整的命名空間+文件名來加載/訪問資源。使用ResourceManager和nameof運算符查找文字資源鍵

var rm = new ResourceManager("namespace.name.locale.brand", Assembly.GetExecutingAssembly()); 

我通過'myImage'以非重構安全方法訪問我的資源圖像。

string imageUrl = rm.GetString("myImage"); 

想象一下,我有許多不同的區域設置/品牌名稱的.resx文件。他們都有不同的圖像,但他們有相同的密鑰。因此,我無法訪問靜態類型的資源,因爲我只是在運行時知道正確的資源。

但我希望有一個與nameof操作符和資源管理器實例相結合的棘手方法。

任何人都知道棘手的方式?

請不要建議以靜態類型的方式訪問這些.resx文件中的任何文件,並將nameof的密鑰傳遞給上述.GetString()方法。

如果沒有與nameof操作沒有解決任何工具是值得歡迎的THEN太;-)

回答

0

既然你不想有靜態類型資源,還有比手動更新代碼沒有別的辦法。

但是,您仍然可以創建一個包裝來訪問資源。通過創建包裝器,您可以集中訪問單個文件,並且還可以使用重命名F2對其進行一次全部更改。

public class ResourceWrapper 
{ 
    private ResourceManager rm; 

    public ResourceWrapper(string name) : 
     this(name, Assembly.GetCallingAssembly()) 
    { 
    } 
    public ResourceWrapper(string name, Assembly assembly) 
    { 
     rm = new ResourceManager(name, assembly); 
    } 

    public string myImage => rm.GetString(nameof(myImage)); 
} 

或者,您可以靜態鏈接到一個資源文件中,並把它作爲nameof名提供商。像:

string imageUrl = rm.GetString(nameof(DummyResource.myImage)); 
相關問題