是否有可能在Visual Studio(2013)类图中配置关联,以便当代码从中生成时,它会创建类型为List<MyClass>
甚至ICollection<MyClass>
的属性,而不是默认的IEnumerable<MyClass>
?
是的,可以更改输出。Visual Studio使用T4模板从架构工具生成代码。
您可以在C:Program Files (x86)Microsoft Visual Studio 12.0Common7IDEExtensionsMicrosoftArchitecture ToolsExtensibility templates Text(如果您有32位机器,请删除(x86))中找到模板。
使用以下步骤将生成的代码更改为IList<T>
而不是默认的IEnumerable<T>
:
- 将所有模板备份到机器上的不同目录(宁可安全也不要后悔)
- CSharpHelper开放。从上面的目录
-
找到名为
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; }
-
将字符串IEnumerable更改为您想要的任何内容(参见我的评论以SO开头)
- 保存T4文件并从visual studio 生成代码
您甚至可以编写自己的T4模板,并指示visual studio在生成代码时使用它们,更多详细信息请访问MSDN。