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; }
}

它用于通过我的 url 助手类上的属性添加路由,该类包含我网站中的 url 列表,因此我有一种简单的方法来管理我的网站 url。

但是添加默认值时遇到问题,出现编译器错误:

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

为避免混淆,将值设置为 routeurl,物理 url 来自属性,原因是,我正在转换现有网站,而不是到处更改链接,一旦我完成页面,我就去上课并将物理网址更改为新页面

给出错误:

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

4

2 回答 2

1

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

该错误准确地告诉您问题所在。

作为

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

不是常量表达式,不是 typeof 表达式,也不是数组创建表达式,这是不合法的。

于 2011-02-25T14:50:04.540 回答
1

属性构造函数的参数值存储在元数据中。这对您可以指定的内容施加了严格的限制。只是简单的值类型,来自 typeof 的类型和这些值的简单一维数组。不允许任何代码,这是编译器抱怨的,new运算符需要代码。

您可以在属性构造函数的主体中执行的操作没有任何限制,该代码稍后在反射代码检查属性时运行。建议类似的东西:

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" }
}

This obviously needs work, I have no idea what the dictionary means. Be careful about it having side-effects or requiring resources, you don't know the runtime state when the attribute gets constructed.

于 2011-02-25T15:21:55.287 回答