smd*_*ger 7 c# templates programming-languages metaprogramming
有没有任何语言形式的代码模板?让我解释一下我的意思......我今天正在研究一个C#项目,其中我的一个类是非常重复的,一系列属性的getter和setter.
public static int CustomerID
{
get
{
return SessionHelper.Get<int>("CustomerID", 0); // 0 is the default value
}
set
{
SessionHelper.Set("CustomerID", value);
}
}
public static int BasketID
{
get
{
return SessionHelper.Get<int>("BasketID", 0); // 0 is the default value
}
set
{
SessionHelper.Set("BasketID", value);
}
}
... and so forth ...
Run Code Online (Sandbox Code Playgroud)
我意识到这可以分解为基本上类型,名称和默认值.
我看到这篇文章,与我想象的类似,但没有参数空间(默认).
但我在想,很多时候代码都会分解成模板.
例如,语法可以这样:
public template SessionAccessor(obj defaultValue) : static this.type this.name
{
get
{
return SessionHelper.Get<this.type>(this.name.ToString(), defaultValue);
}
set
{
SessionHelper.Set(this.name.ToString(), value);
}
}
public int CustomerID(0), BasketID(0) with template SessionAccessor;
public ShoppingCart Cart(new ShoppingCart()) with template SessionAccessor; // Class example
Run Code Online (Sandbox Code Playgroud)
我觉得这有很多可能性来编写简洁,干燥的代码.这种类型的东西在c#中可以通过反射实现,但是这很慢,这应该在编译期间完成.
所以,问题:在任何现有的编程语言中,这种功能是否可行?
正如Marc Gravell评论的那样,T4(文本模板转换工具包)是一个简单的工作,它是一个集成在Visual Studio中的模板处理器,可以与C#或VB一起使用,并且可以生成任何内容.它是一个工具,而不是内置语言功能.
将文本模板文件(.tt)添加到项目中,模板将如下所示:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".generated.cs" #>
<#
var properties = new[] {
new Property { Type = typeof(int), Name = "CustomerID", DefaultValue = 0 },
new Property { Type = typeof(int), Name = "BasketID", DefaultValue = 0 },
};
#>
namespace YourNameSpace {
public partial class YourClass {
<# foreach (Property property in properties) { #>
public static <#= property.Type.FullName #> <#= property.Name #> {
get { return SessionHelper.Get<<#= property.Type.FullName #>>("<#= property.Name #>", <#= property.DefaultValue #>); }
set { SessionHelper.Set("<#= property.Name #>", value); }
}
<# } #>
}
}
<#+
public class Property {
public Type Type { get; set; }
public string Name { get; set; }
public object DefaultValue { get; set; }
}
#>
Run Code Online (Sandbox Code Playgroud)
T4非常适合这种代码生成.我强烈建议T4 Toolbox轻松生成每个模板的多个文件,访问EnvDTE直接在Visual Studio中解析现有的C#代码和其他优点.