有没有一种语言具有代码模板的形式?让我解释一下我的意思... 今天我在做一个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 ...
我意识到这可以基本上分解为一种类型、一个名称和一个默认值。
我看到了这篇文章,与我所设想的类似,但没有参数(默认)的空间。 在C#中的通用属性 但我在想,有很多时候代码会被分解成模板。
例如,语法可以如下所示:
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
我觉得这会在编写简洁、DRY代码方面有很多可能性。通过反射,c#可以实现这种类型的功能,但是速度较慢,因此应该在编译期间完成。
问题是:是否有任何现有的编程语言可以实现这种类型的功能?