如何在T4模板使用的resx资源文件 [英] How to use a resx resource file in a T4 template

查看:168
本文介绍了如何在T4模板使用的resx资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何以包括(.TT)T4模板资源文件(的.resx)。

I cant figure out how to include the resource file (.resx) in the (.tt) T4 template.

我试过到目前为止...导入命名空间

I tried so far... Importing the namespace

<#@ import namespace="T4TemplateResources.resx" #>



此外,包括类

Also including the class

推荐答案

尼科的解决方案需要您的解决方案来构建。

Nico's solution requires your solution to build.

有另一种方法,而无需通过读取原始RESX文件来编译您的解决方案。

There is another way, without needing to compile your solution by reading the raw resx file.

    var fileName = "CustomResource.resx";
    var filePath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "WindowsFormsApplication1", fileName);
    var reader = new ResXResourceReader(filePath);
    var values = reader.Cast<DictionaryEntry>().ToDictionary(x => x.Key, y => y.Value);

    // this is how you would acces the resources
    var value = values["entry"];

您应该知道,这种方法缺乏设计时检查,如果资源不存在,而你不知道'吨得到本地化的值,因为你只是读文件。两者往往不是强制性withing T4模板

You should be aware that this method lacks design time checking if the resource does not exist and you don't get localized values because you are just reading a file. Both are often not mandatory withing T4 templates

下面是一个工作剪断创建从一个资源文件的枚举。

Here is a working snipped that creates an enum from a resource file.

只要确保你使用文件名设置正确的价值观文件路径

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>

<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>

<#

    var nameSpace = "WindowsFormsApplication1";
    var enumName = "CustomEnum";

    var fileName = "CustomResource.resx";
    var filePath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "WindowsFormsApplication10", fileName);

    using (var reader = new ResXResourceReader(filePath))
    {

        reader.UseResXDataNodes = true;
#>

namespace <#=nameSpace#>
{

    public enum <#=enumName#>
    {

        Undefined,

        <#  foreach(DictionaryEntry entry in reader) { 

            var name = entry.Key;
            var node = (ResXDataNode)entry.Value;
            var value = node.GetValue((ITypeResolutionService) null);
            var comment = node.Comment;
            var summary = value;
            if (!String.IsNullOrEmpty(comment)) summary += " - " + comment;
        #>

        /// <summary>
        /// <#= summary #>
        /// </summary>
        <#= name #>,

        <# } #>

    }

}


<#
    }
#>

这篇关于如何在T4模板使用的resx资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆