【问题标题】:Visual Studio Architecture Code Generation - Create List<type> rather than IEnumerable<type>Visual Studio 体系结构代码生成 - 创建 List<type> 而不是 IEnumerable<type>
【发布时间】:2014-06-28 20:06:50
【问题描述】:

是否可以在 Visual Studio (2013) 类图中配置关联,以便在从中生成代码时创建类型为 List&lt;MyClass&gt; 甚至 ICollection&lt;MyClass&gt; 的属性,而不是默认的 @987654323 @?

【问题讨论】:

    标签: c# visual-studio code-generation


    【解决方案1】:

    是的,可以更改输出。 Visual Studio 使用 T4 模板从体系结构工具生成代码。

    您可以在 C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Architecture Tools\Extensibility\Templates\Text 找到模板(删除 (x86) 如果您有 32 位机器)。

    使用以下步骤将生成的代码更改为IList&lt;T&gt;,而不是默认的IEnumerable&lt;T&gt;

    1. 将所有模板备份到您机器上的不同目录(安全胜于遗憾)
    2. 从上述目录打开 CSharpHelper.t4
    3. 找到名为ElementType(IType type, bool isEnumerable = false)的方法

       private static string ElementType(IType type, bool isEnumerable = false)
      {
          string text = string.Empty;
          if (type == null)
          {
              text = "object";
          }
          else 
          {
              text = TypeName(type);
          }
      
          if(!string.IsNullOrWhiteSpace(text) && isEnumerable)
          {
             //SO Change IEnumerable to IList here
              text = "IEnumerable<" + text + ">";
          }
      
          return text;
      }
      
    4. 将字符串 IEnumerable 更改为您想要的任何内容(请参阅我以 SO 开头的评论)

    5. 保存 T4 文件并从 Visual Studio 生成代码

    您甚至可以编写自己的 T4 模板并指示 Visual Studio 在生成代码时使用它们,更多详细信息请参见 MSDN

    【讨论】:

    • 非常感谢您提供如此详细的答案,尤其是链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2015-04-26
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多