Declare Lambda Expression as a class constant field

喜夏-厌秋 提交于 2020-01-04 04:43:04

问题


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

But I get the compile error: Expression cannot contain anonymous methods or lambda expressions


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19198037/declare-lambda-expression-as-a-class-constant-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!