C# 属性中的Lambda表达式
我有一个名为Mod的静态类和一个名为Map的静态函数:C# 属性中的Lambda表达式,c#,custom-attributes,lambda,C#,Custom Attributes,Lambda,我有一个名为Mod的静态类和一个名为Map的静态函数: public static class Mod<TModel> { public static string Map<TValue>(Expression<Func<TModel, TValue>> expression) { throw new Exception("Not implemented"); } } 为什么我不能这样称呼它 [Attrib
public static class Mod<TModel>
{
public static string Map<TValue>(Expression<Func<TModel, TValue>> expression)
{
throw new Exception("Not implemented");
}
}
为什么我不能这样称呼它
[Attributes.MyTest(Attributes.Mod<string>.Map<string>(x => x.ToLower()))]
public string SomeProperty { get; set; }
[Attributes.MyTest(Attributes.Mod.Map(x=>x.ToLower())]
公共字符串SomeProperty{get;set;}
我得到错误“表达式不能包含匿名方法或lambda表达式”。但是为什么呢
我很清楚lambda表达式在属性中不起作用。。。但是为什么带有lambda的静态类/静态方法不能作为属性的参数工作(…如果这是我遇到的问题的话)
感谢,因为您传递给属性构造函数的值应该是编译时常量。并且您的方法的结果不是常量,因为它在编译时未知。因此这实际上不是lambda表达式所特有的,它只能是其中之一,如错误消息中所述: 属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式
public class MyTestAttribute : Attribute
{
public MyTestAttribute(string label)
{
}
}
[Attributes.MyTest(Attributes.Mod<string>.Map<string>(x => x.ToLower()))]
public string SomeProperty { get; set; }