为什么不能声明 type 的类常量字段Lambda Expression
。我想要这样的东西:
class MyClass
{
public const Expression<Func<string,bool>> MyExpr = (string s) => s=="Hello!";
}
但我得到编译错误:Expression cannot contain anonymous methods or lambda expressions
为什么不能声明 type 的类常量字段Lambda Expression
。我想要这样的东西:
class MyClass
{
public const Expression<Func<string,bool>> MyExpr = (string s) => s=="Hello!";
}
但我得到编译错误:Expression cannot contain anonymous methods or lambda expressions
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.
Reproduced. That is a strange error message from the compiler. I would expect instead:
error CS0134: '(field)' is of type '(type)'. A const field of a reference type other than string can only be initialized with null.
The message we do get is misleading. Some C# expressions (I am not talking about .NET expression trees Expression<...>
) can clearly contain a lambda expression, but they don't say why this particular expression cannot.
The solution is to make a static readonly
field instead:
class MyClass
{
public static readonly Expression<Func<string, bool>> MyExpr
= s => s == "Hello!";
}
Only one instance of Expression<>
will ever be created, but it is no compile-time constant, there is actually some code that will run once (just) before MyClass
is used for the first time.