定义局部变量常量VS类常量 [英] Defining Local Variable const vs Class const

查看:212
本文介绍了定义局部变量常量VS类常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用的是常量,它是仅在一个方法需要的,它是最好的方法范围内声明的常量,或在类范围内?是否有更好的表现,宣布它的方法是什么?如果这是真的,我认为这是更标准在类的范围内(文件的顶部)来定义他们改变的价值和重新编译更容易。

 公共类鲍勃
{
   私人const int的SomeConst = 100; //这里声明它?
   公共无效的MyMethod()
   {
      const int的SomeConst = 100; //或此申报呢?
      //做soemthing与SomeConst
   }
}
 

解决方案

有一个在移动不断进级没有性能增益。 CLR的是足够聪明的认识常量不变,所以尽量表现的推移两者相等。什么,当你编译成IL实际情况是,该常量的值是硬codeD插入编译器为文字值的程序。

在换句话说,一个常数不是一个引用内存位置。这不像是一个变量,它更像一个文字。常量是在多个地点在code同步文字。所以,它给你 - 虽然这是整洁的编程限制常数到它是相关的范围

If I am using a constant that is needed only in a method, is it best to declare the const within the method scope, or in the class scope? Is there better performance declaring it in the method? If that is true, I think it's more standard to define them at class scope (top of file) to change the value and recompile easier.

public class Bob
{
   private const int SomeConst = 100; // declare it here?
   public void MyMethod()
   {
      const int SomeConst = 100; // or declare it here?
      // Do soemthing with SomeConst
   }
}

解决方案

There is no performance gain in moving the constant into the class. The CLR is smart enough to recognize constants as constant, so as far as performance goes the two are equal. What actually happens when you compile to IL is that the values of the constants are hardcoded into the program by the compiler as literal values.

In other words, a constant is not a referenced memory location. It is not like a variable, it's more like a literal. A constant is a literal synced across multiple locations in your code. So it's up to you - though it's neater programming to limit the scope of the constant to where it is relevant.

这篇关于定义局部变量常量VS类常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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