2011-02-25 35 views
1

我創建了一個自定義屬性稱爲RouteAttribute屬性幫助的路由,編譯器錯誤

[AttributeUsage(AttributeTargets.Property)] 
public class RouteAttribute : Attribute 
{ 
    public string Url { get; set; } 
    public bool CheckPhysicalUrlAccess { get; set; } 
    public RouteValueDictionary Defaults { get; set; } 
    public RouteValueDictionary Constraints { get; set; } 
    public RouteValueDictionary DataTokens { get; set; } 
} 

它是用來增加通過包含在我的網站網址的名單上我的網址助手類屬性的路由,所以我有一個簡單的方法來管理我的網站網址。

有一個問題,與添加默認不過,讓編譯器錯誤:

[Route("~/MyPage/Home.aspx", new RouteValueDictionary { { "query", "value" } })] 
public string HomePage 
{ 
    get { return "Home" } 
} 

爲了避免混淆,該值設置爲routeurl,物理地址是從屬性, 原因是,我轉換現有的網站,而不是改變聯繫無處不在,一旦我與網頁做,我去我的階級和改變物理鏈接到新的頁面

給了一個錯誤:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

回答

1

屬性構造函數的參數值存儲在元數據中。這對你可以指定的內容有嚴格的限制。只是簡單的值類型,Typeof的Type和這些值的簡單一維數組。沒有代碼是允許的,這是編譯器的抱怨,新的運營商需要代碼。

在屬性構造函數的主體中可以做什麼沒有限制,稍後代碼在反射代碼檢查屬性時運行。建議類似這樣的:

public class RouteAttribute : Attribute 
{ 
    public RouteAttribute(string url, string query, string value) { 
     this.url = url; 
     this.dunno = new RouteValueDictionary(query, value); 
    } 
    // etc.. 
} 
... 
[Route("~/MyPage/Home.aspx", "query", "value")] 
public string HomePage 
{ 
    get { return "Home" } 
} 

這顯然需要工作,我不知道字典的含義。要小心它有副作用或需要資源,當屬性被構造時,你不知道運行時狀態。

+0

不是最好的解決方案,但它的工作原理..我將在未來研究更好的方式,謝謝 – jaekie 2011-02-25 16:49:34

1

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

該錯誤告訴你到底是什麼問題。

作爲

new RouteValueDictionary { { "query", "value" } } 

不是一個常量表達式,而不是一個typeof運算表達式,而不是一個數組創建表達式,這是不合法的。