gpt4 book ai didi

c# - 在 C# 中将常量强制转换为 var

转载 作者:行者123 更新时间:2023-12-02 22:02:52 24 4
gpt4 key购买 nike

给定以下条件,C# 编译器有多聪明:

float a = 1; //A
var b = 1f; //B
var c = (float)1; //C - Is this line equivalent to A and B?
var d = Convert.ToSingle(1); //D - Is this line equivalent to A and B?

据我所知,编译后A和B是等价的。其他线路呢?

C 和 D 是否在编译时优化为等同于 A 和 B,或者它们是否仅在运行时分配,导致更多处理来执行分配?

我认为转换 (C) 必须优化,而函数 (D) 不能。

无论如何,我该如何调查和比较使用 VS2012 生成的汇编代码?

最佳答案

前三行是等价的;事实上,它们编译成相同的 IL(至少使用我使用的 .NET 4 编译器)。

第四种是通过调用方法执行的运行时转换,这是完全不同的野兽。

关于生成IL的检查,看A tool for easy IL code inspection .

关于c# - 在 C# 中将常量强制转换为 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com