2

例如,我一直在使用资源文件并在我的视图中引用它们Resources.Labels.CountryName。但是我有一种情况,我需要从资源名称作为字符串获取 C# 中资源的值,即

string resourceName = "Resource.Labels.CountryName";

我如何从这个字符串中获取资源文件中的值?

4

1 回答 1

2

通常你会得到资源

GetLocalResourceObject("~/VirtualPath", "ResourceKey");
GetGlobalResourceObject("ClassName", "ResourceKey");

你可以适应这个。我为 HTML 帮助器编写了自己的扩展,就像这个用于全局资源的扩展:

public static string GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
{
    var resource = htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey);
    return resource != null ? resource.ToString() : string.Empty;
}

我认为,在您的示例中,您将使用@Html.GetGlobalResource("Labels", "CountryName").

因为本地资源需要虚拟路径,我不想写到视图中,所以我使用了这个组合,这两个机会:

public static string GetLocalResource(this HtmlHelper htmlHelper, string virtualPath, string resourceKey)
{
    var resource = htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(virtualPath, resourceKey);
    return resource != null ? resource.ToString() : string.Empty;
}

public static string Resource(this HtmlHelper htmlHelper, string resourceKey)
{
    var virtualPath = ((WebViewPage) htmlHelper.ViewDataContainer).VirtualPath;
    return GetLocalResource(htmlHelper, virtualPath, resourceKey);
}

With that you can get a local resource very comfortable by writing @Html.Resource("Key") in your view. Or use the first method to get local resources of other views like with @Html.GetLocalResource("~/Views/Home/AnotherView.cshtml", "Key").

于 2013-04-07T20:14:10.337 回答