C#中readonly和const之间的区别 [英] difference between readonly and const in C#

查看:102
本文介绍了C#中readonly和const之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的应用程序中调用了一个库(dll)的字符串常量值。那么应该使用什么,即readonly或constamt用于库中的常量。有什么区别?



如果这个问题太天真,请原谅我。



谢谢。

I am calling some string constant value of a library (dll) from my application. So what should use i.e. readonly or constamt for those constant in the library. What is the difference?

Please forgive me if this question is too naive.

Thanks.

推荐答案

不,这是一个很好的问题,不是那么天真。常量有一个限制:它的值应该是静态知道的。这意味着,在编译期间已知。例如,某些功能的计算结果是未知的;它的值只能在运行时计算。



No, this is a good question, not so naive. Constant has one limitation: its value should be "statically known". It means, known during compilation. Such thing as, for example, a result of calculation of some function is not known; its value can be calculated only during run-time.

static class NonModifiableDeclarationSet {
    internal const int SomeInteger = 5;
    internal const int SomeOtherInteger = SomeInteger * 10; //constant expression
    // won't compile:
    //internal const double SomeFloatingPointValue = System.Math.Acos(-1d);
    // will work:
    internal static readonly double SomeFloatingPointValue = System.Math.Acos(-1d);
}





在此示例中, SomeFloatingPointValue 将在初始化期间初始化运行时间到使用它的时刻,但它在初始化后无法修改,这对于维护和作为一个万无一失的功能非常重要。它也可以在构造函数中初始化。使用 const 无法实现此效果。



请参阅:

< a href =http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.100%29.aspx> http://msdn.microsoft.com/en-us/library/acdd6hb7 %28v = vs.100%29.aspx [ ^ ]。



-SA



In this example, SomeFloatingPointValue will be initialized during run time when by the moment it is used, but it cannot be modified after it it initialized, which important for maintenance and as a fool-proof feature. It can also be initialize in a constructor. This effect could not be achieved with const.

Please see:
http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.100%29.aspx[^].

—SA


一个区别是



常量值将嵌入可执行的文件在编译时,并在任何使用它的地方替换它。因此,如果您的应用程序引用了库中的常量值,那么您的应用程序也需要重新编译。



程序在运行时读取只读变量。因此,如果在应用程序引用的库中更改只读变量的值,而不重新编译应用程序,则只读变量的新值将由程序阅读。



添加一个例子来详细阐述以上几点[/ edit]

One difference is that

A constant value will be embedded in the executable file at compile time, and substitutes it at all places wherever it is used. So, if the constant value is changed in the library, which is referenced by your application, then your application also requires to be re-compiled.

A read only variable is read by the program at run time. So, if the value of the read only variable is changed in the library, which is referenced by your application, without recompiling your application, the new value of the read only variable will be read by the program.

[edit]An example added to elaborate the above points[/edit]
//Project 1. Main application
using System;

namespace ConstReadOnlyTest {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Value of Constant from Library: {0}", SupportingLib.Class1.ConstString);
            Console.WriteLine("Value of Read ony variable from Library: {0}",SupportingLib.Class1.ReadOnlyString);
            Console.ReadKey();
        }
    }
}
//Project 2. Referenced library, procured from other company say Comapany A.
//The version of compile lib is say 1.0.0.0
using System;

namespace SupportingLib {
    public class Class1 {
        public const string ConstString = "Constant";
        public static readonly string ReadOnlyString = "Readonly";
    }
}





当我编译此代码并运行它时输出为



When I compile this code and run it the output is

Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly



我的应用程序已发货。之后,在引用的库中进行了更改

和A公司为我提供了相同版本1.0.0.0的新编译库



这是引用库中已更改的代码


My application is shipped. Later, a change is made in the referenced library
and Company A supplied me new compiled library with same version 1.0.0.0

This is the changed code in the referenced library

public const string ConstString = "Constant Changed";
public static readonly string ReadOnlyString = "Readonly Changed";





如果不重新编译我的应用程序,我只向用户提供了引用库的新编译版本。然后输出是





Without recompiling my application I have only supplied the new compiled version of the referenced library to the user. Then the output is

Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly Changed





我编译应用程序的原因是从引用的程序集中复制了字符串Constant,并将其放在我的可执行代码中。然而,对于只读变量,程序在运行时从引用的程序集读取。



因此,当我提供新的编译库时,程序确实从中读取了只读变量新编译的引用库。因此,在第二行输出中,我们得到了:Readonly Changed

而程序在我的应用程序中使用常量,因此在第一行打印Constant值。



希望我澄清了我的想法。



The reason being when I compiled my application the string "Constant" was copied from the referenced assembly and placed in my executable code. Whereas, for Read only variable the program reads from the referenced assembly at run time.

So, when I supplied new compiled library the program did read the read only variable from the new compiled referenced library. Hence in the second line of output we got: "Readonly Changed"
Whereas the program used the constant from within my application so the value "Constant" is printed in the first line.

Hope I clarified what I thought.


'const':

不能是静态的。

价值在编译时评估。

仅在声明时确定。



'readonly':

可以是实例级或静态。

值在运行时计算。

可以在声明中或在构造函数中的代码中初始化。



这意味着仅在构造函数中更改(初始化)的变量应该是只读的。



通常被认为更好地使用readonly因为如果const更改了所有客户端。但是,const更快。
'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

This means that variable that is changed (initialized) only in constructor should be readonly.

It is generally considered better to use readonly because if a const is changed then all the clients. However, const is faster.


这篇关于C#中readonly和const之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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