C#中:什么是常量表达式? [英] c#: what is a constant expression?

查看:214
本文介绍了C#中:什么是常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与此刻的属性工作。我经常碰到的错误'的属性参数必须是常量表达式的typeof属性参数类型的表达式或数组创建表​​达式。我真的不知道什么是常量表达式的意思。

I'm working with attributes at the moment. I often run into the error 'An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.' I don't really know what 'constant expression' means.

这本来是非常有用的,能够在 Func键和下传; MyType的,布尔> 来的属性(由代码饮用执行时的属性存在)。但很可惜,没有。我不明白为什么这类型不能放置在程序集元数据,我以为是我不能把它传递到属性的原因。

It would have been really useful to be able to pass in a Func<MyType, bool> to the attribute (to be consumed by the code which executes when the attribute is present). But alas, no. I don't understand why that type cannot be placed in assembly metadata, which I assume is the reason I cannot pass it into the attribute.

谁能给我任何想法?

推荐答案

编译器需要能够创建在编译时的属性,因为它们嵌入在汇编自身实际数据(它们是由编译器实例化和序列化到输出文件)。这就是为什么你需要一个常量表达式。

The compiler needs to be able to create the Attributes at compile time, since they are embedded in your assembly with their actual data (they are instantiated by the compiler and serialized into the output file). That's why you need a constant expression.

基本上,你可以使用所有的基本数据类型(如 INT BOOL 字符串等)。您还可以使用的typeof 表情,因为他们将被解析为元数据标记标识类型,它是在编译时的罚款。

Basically you can use all the basic data types (like int, bool, string etc.). You can also use typeof expressions because they will be resolved to metadata tokens identifying a type, which is fine at compile time.

也许你可以把你的 Func键<的概念; MyType的,布尔> 成你的类型实现一个接口。或者到一个单独的处理程序类,您可以通过使用 typeof运算(MyHandlerClass)表情传递给你的属性。

Maybe you can put the concept of your Func<MyType, bool> into an interface that your types implement. Or into a separate handler class that you can pass to your Attribute by using a typeof(MyHandlerClass) expression.

这篇关于C#中:什么是常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆