Visual Studio架构代码生成 - 创建List<type>而不是IEnumerable<type>

5

是否可以在Visual Studio(2013)类图中配置关联,以便在从中生成代码时创建具有类型List<MyClass>或甚至ICollection<MyClass>的属性,而不是默认值IEnumerable<MyClass>

1个回答

6
是的,可以更改输出。Visual Studio使用T4模板从架构工具生成代码。
你可以在 C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Architecture Tools\Extensibility\Templates\Text 中找到这些模板(如果你的计算机是32位的,则删除(x86))。
按照以下步骤将生成的代码更改为IList<T>而不是默认的IEnumerable<T>
  1. Back up all templates to a different directory on your machine (better be safe than sorry)
  2. Open CSharpHelper.t4 from the above directory
  3. Locate the method named 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. Change the string IEnumerable to whatever you want (see my comment starting with SO)

  5. Save the T4 file and generate your code from visual studio

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


非常感谢您提供如此详细的答案,特别是提供链接。非常优秀! - Andrew Maggs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接