是否有任何具有代碼模板形式的語言?讓我解釋我的意思......我今天正在研究一個C#項目,其中我的一個類是非常重複的,一系列屬性獲得者和設置者。有沒有使用代碼模板的語言?
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 ...
我意識到這可能分解成基本類型,名稱和默認值。
我看到這篇文章,它與我設想的類似,但沒有參數空間(默認)。
但我在想,有很多次,代碼分解成模板。
例如,語法可以去這樣:
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#中可以通過反射實現,但是這很慢,這應該在編譯期間完成。
所以,問題:這種類型的功能可能在任何現有的編程語言中?
聽起來像T4的工作給我... –
C++有模板,接近你想要的:http://www.cplusplus.com/doc/tutorial/templates/ –
如果你主要關心的是單調乏味地進入樣板(而不是在你的樣板中改變的可能性),Resharper有一個不錯的實時模板功能,這真的有助於這一點。 T4功能更強大(您可以更新模板定義並使用更新後的模板重新生成文件),但它也增加了一些額外的複雜性。香草VS有代碼片段,這也可以幫助。 –