c# - 在 visual studio 中自动生成部分类的扩展

标签 c# visual-studio

这是我想做的。

我想像这样编写 POCO 类:

[AutoExtended]
public partial class Foo {
    public int Bar;
    public string Baz;
}

最好在我的解决方案中的任意文件中([AutoExtend] 属性是我为了识别感兴趣的类而编写的)。

我希望构建过程从 (a) 在我的源代码中查找这些 AutoExtend 类开始,并且 (b) 像这样自动生成扩展:

public partial class Foo {
    public static SomeType<int> Bar(Foo x) { ... };
    public static SomeOtherType<string> Baz(Foo x) { ... };
}

在编译解决方案之前。

有谁知道如何最好地做到这一点?我想 Roslyn 是必经之路,但我乐于接受建议。理想情况下,我想要一个解决方案,除了 AutoExtend 属性之外,用户方面需要零额外的“管道”。

(如果有人感兴趣,我正在用 C# 类和重载运算符编写一种领域特定语言,上述内容将使 DSL 使用起来更加舒适。)

最佳答案

正如评论中所建议的那样,使用 T4 是非常可行的。

关于构建时的转换,您可以使用 <TransformOnBuild> 来完成.csproj 文件中的属性。见this question ,特别是@Cheburek 的回答。还有更多信息on MSDN .

然后使用 AutoExtend 定位类您需要使用 EnvDTE 而不是反射属性,因为任何现有程序集都将过时。

类似于:

<#
// get a reference to the project of this t4 template
var project = VisualStudioHelper.CurrentProject;

// get all class items from the code model
var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);

// iterate all classes
foreach(EnvDTE.CodeClass codeClass in allClasses)
{
        // get all attributes this method is decorated with
        var allAttributes = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Attributes, vsCMElement.vsCMElementAttribute, false);
        // check if the SomeProject.AutoExtendedAttribute is present
        if (allAttributes.OfType<EnvDTE.CodeAttribute>()
                         .Any(att => att.FullName == "SomeProject.AutoExtended"))
        {
        #>
        // this class has been generated
        public partial class <#= codeClass.FullName #>
        {
          <#
          // now get all methods implemented by the class
          var allFunctions = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementFunction, false);
          foreach(EnvDTE.CodeFunction function in allFunctions)
          {
          #>
              public static <#= function.FullName #> etc...
          <#
          } 
          #>
        }
<#          
        }
    }
}
#>

关于c# - 在 visual studio 中自动生成部分类的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653991/

相关文章:

c# - 列出一个月中的所有日期 ASP.NET C#

c# - 监听套接字-连接套接字已连接,而在EndAccept上没有调试中断

c# - 如何将所有对象从一个 IList 移动/复制到另一个

C# 后台 worker 不会在我自己以外的任何电脑上触发 dowork 事件

.net - 如何根据开发人员的操作系统架构在 Visual Studio 中复制文件?

C++ 奇怪的访问冲突 Visual Studio 2015 RC

.net - 内容文件更改后 Visual Studio 未重建

c# - 在 asp.net mvc 中以编程方式中止 OutputCache 持续时间

html - Regex Match 内部匹配

asp.net-mvc - 从 IP 地址远程访问本地 ASP.NET Core 应用程序?