2011-09-09 30 views
7

是否有任何具有代碼模板形式的語言?讓我解釋我的意思......我今天正在研究一個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 ... 

我意識到這可能分解成基本類型,名稱和默認值。

我看到這篇文章,它與我設想的類似,但沒有參數空間(默認)。

Generic Property in 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#中可以通過反射實現,但是這很慢,這應該在編譯期間完成。

所以,問題:這種類型的功能可能在任何現有的編程語言中?

+8

聽起來像T4的工作給我... –

+2

C++有模板,接近你想要的:http://www.cplusplus.com/doc/tutorial/templates/ –

+0

如果你主要關心的是單調乏味地進入樣板(而不是在你的樣板中改變的可能性),Resharper有一個不錯的實時模板功能,這真的有助於這一點。 T4功能更強大(您可以更新模板定義並使用更新後的模板重新生成文件),但它也增加了一些額外的複雜性。香草VS有代碼片段,這也可以幫助。 –

回答

9

正如Marc Gravell所評論的,T4 (Text Template Transformation Toolkit)是一個簡單的工作,它是一個集成在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; } 
} 
#> 

T4是偉大的這種代碼生成的。我強烈建議使用T4 Toolbox輕鬆地爲每個模板生成多個文件,訪問EnvDTE直接在Visual Studio中解析現有的C#代碼和其他優點。

+1

對於一個好的初學者博客:http://www.olegsych。com/2007/12/text-template-transformation-toolkit/ – FuleSnabel

+0

只是FYI; T4可以生成C#,C++,C,ObjectiveC,XML,基本上是任何文本。它爲我節省了幾個月的繁瑣可怕的重複性工作。 – FuleSnabel

9

...你已經發現了metaprogramming的美妙世界。歡迎! :-)

原型元編程語言是Lisp,或者真的可以用代碼表示其自己的結構的任何其他語言。

其他語言試圖在一定程度上覆制這個; macros in C是一個突出的例子。

最近在某種程度上支持這種語言的着名候選語言是C++ via its templatesRuby

相關問題