我有一个名为Mod的静态类,它带有一个名为Map的静态函数:
public static class Mod<TModel>
{
public static string Map<TValue>(Expression<Func<TModel, TValue>> expression)
{
throw new Exception("Not implemented");
}
}
我可以执行这样的方法(没问题):
var test = Mod<string>.Map<string>(x => x.ToLower());
我的构造函数中有一个带字符串参数的属性:
public class MyTestAttribute : Attribute
{
public MyTestAttribute(string label)
{
}
}
为什么我不能这样称呼它?
[Attributes.MyTest(Attributes.Mod<string>.Map<string>(x => x.ToLower()))]
public string SomeProperty { get; set; }
我得到错误&#34;表达式不能包含匿名方法或lambda表达式&#34;。但为什么呢?
我很清楚lambda表达式在属性中不起作用......但是为什么用lambda作为属性的参数来赢得静态类/静态方法(...如果那样&#39 ;我遇到的问题)?
由于
答案 0 :(得分:2)
因为您传递给Attribute的构造函数的值应该是编译时常量。并且您的方法的结果不是常量,因为它在编译时是未知的。所以这实际上并不特定于lambda表达式,它只能是错误消息中解释的其中一个:
属性参数必须是属性参数类型
的常量表达式,typeof表达式或数组创建表达式