Visual Studio Architecture Code Generation - Create List<type> rather than IEnumerable<type>

孤人 提交于 2019-12-21 14:52:10

问题


Is it possible to configure an Association in a Visual Studio (2013) class diagram so that when the code is generated from it that it creates a property with type List<MyClass> or even ICollection<MyClass> rather than it's default of IEnumerable<MyClass>?


回答1:


Yes, it is possible to change the output. Visual Studio uses T4 templates to generate code from the Architecture tools.

You can find the templates at C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Architecture Tools\Extensibility\Templates\Text (remove (x86) if you have a 32-bit machine).

Use the following steps to change the generated code to IList<T> instead of the default 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

You can even write your own T4 Templates and instruct visual studio to use them when generating code, more details on MSDN.



来源:https://stackoverflow.com/questions/23592471/visual-studio-architecture-code-generation-create-listtype-rather-than-ienum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!