这就是我想做的事情.
我想写这样的POCO类:
[AutoExtended]
public partial class Foo {
public int Bar;
public string Baz;
}
Run Code Online (Sandbox Code Playgroud)
最好是在我的解决方案中的任意文件中([AutoExtend]属性是我刚刚编写的用于识别interes类的东西).
我希望构建过程从(a)AutoExtend在我的源代码中查找这些类开始,以及(b)自动生成如下的扩展:
public partial class Foo {
public static SomeType<int> Bar(Foo x) { ... };
public static SomeOtherType<string> Baz(Foo x) { ... };
}
Run Code Online (Sandbox Code Playgroud)
在编译解决方案之前.
有谁知道如何最好地做到这一点?我想罗斯林是要走的路,但我愿意接受建议.理想情况下,我想要一个解决方案,除了AutoExtend属性之外,用户方面不需要额外的"管道" .
(如果有人感兴趣的话,我正在用C#类编写一个域特定语言,并且运算过载,以上情况会使DSL使用起来更加舒适.)
正如评论中所建议的那样,T4非常可行.
关于转换构建,您可以使用.csproj文件中的<TransformOnBuild>属性来执行此操作.看到这个问题,特别是@ Cheburek的回答.有关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...
<#
}
#>
}
<#
}
}
}
#>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |