将Lambda表达式声明为类常量字段 [英] Declare Lambda Expression as a class constant field
本文介绍了将Lambda表达式声明为类常量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么不能声明类型为 Lambda Expression
的类常量。我想要这样的东西:
Why isn't it possible to declare a class constant filed of type Lambda Expression
. I want Something like this:
class MyClass
{
public const Expression<Func<string,bool>> MyExpr = (string s) => s=="Hello!";
}
但是我得到了编译错误:表达式不能包含匿名方法或lambda表达式
But I get the compile error: Expression cannot contain anonymous methods or lambda expressions
推荐答案
这只是C#和CLR的局限性。只有原始数值,字符串文字和<$ c $ c> null 可以用作常量字段的值。表达式树表示为对象的普通图,不能显示为常量。
This is just a limitation of C# and CLR. Only primitive numeric values, string literals and null
can be used as a value of a constant field. Expression trees are represented as a normal graph of objects and can't appear as a constant value.
这篇关于将Lambda表达式声明为类常量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文