为什么我们不能添加 lambda 作为属性参数?例如我想这样做:
[MyAttribut(Transform= {object => object.ToSomethingElse()})]
我应该理解 C# 中的 lambda 只是闭包吗?
编辑:通过查看所有答案,让我确定一件大多数人似乎不知道的事情: 除非是闭包,否则 Lambda 是一个编译时结构。
最佳答案
属性的参数需要是编译时常量。
来自 MSDN - Attribute Parameter Types :
Values passed to attributes must be known to the compiler at compile time.
它们也仅限于这些类型:
- bool
- 字符,无符号字符
- 短,无符号短
- 整数,无符号整数
- long, unsigned long
- __int64,无符号 __int64
- float ,双
- wchar_t
- char* 或 wchar_t* 或 System::String*
- 系统::类型^
- 系统::对象^
- 枚举
关于c# - 属性参数中的 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951378/