常量值属性(Constant value properties)

编程入门 行业动态 更新时间:2024-10-26 08:32:26
常量值属性(Constant value properties)

将非虚拟属性设置为常量值是否可以在编译时进行评估? (就像常量本身一样)

例:

class Clazz { const int SPEED = 5; public int Speed { get { return SPEED; } } }

我知道任何对常量SPEED调用都会在编译时评估一次,但是如果我从程序中的任何位置访问Clazz.Speed 属性 ,那么编译时是否Clazz.Speed进行评估?

编辑:为了稍微解决这个问题, 编译器 (而不是JIT)会内嵌下面两个例子吗? [即。 在编译期间评估]:

// a static / non-static method that returns a constant value (static) int GetConstant() { return 42; } // a static / non-static property that returns a constant value (static) int ConstProperty { get { return 42; } }

Will non-virtual properties to constant values be evaluated in compile time? (Like the constants themselves)

Example:

class Clazz { const int SPEED = 5; public int Speed { get { return SPEED; } } }

I know that any call to the constant SPEED will be evaluated once at compile time, but if I access the Clazz.Speed property from anywhere in my program, will that also be evaluated at compile time?

Edit: To evlove the question a little bit, will the next two examples be inlined by the Compiler (and not the JIT)? [ie. evaluated during compile time] :

// a static / non-static method that returns a constant value (static) int GetConstant() { return 42; } // a static / non-static property that returns a constant value (static) int ConstProperty { get { return 42; } }

最满意答案

通过Linqpad运行它可以为getter生成以下IL:

Clazz.get_Speed: IL_0000: ldc.i4.5 //push integer value 5 on evaluation stack IL_0001: ret

这将意味着getter在运行时(而不是内联)被调用并返回一个常量值。

假设在这种情况下getter将被内联,这意味着如果不需要重新编译任何消费程序集,就不能更改该属性的实现 - 这将首先破坏使用属性。

Running this through Linqpad produces the following IL for the getter:

Clazz.get_Speed: IL_0000: ldc.i4.5 //push integer value 5 on evaluation stack IL_0001: ret

This would mean that the getter is called at runtime (and not inlined) and returns a constant value.

Hypothetically if the getter would be inlined in this case that would mean that the implementation of the property could not be changed without having to recompile any consuming assemblies - this would defeat using a property in the first place.

更多推荐

本文发布于:2023-08-08 01:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466765.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   量值   properties   Constant

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!