c# readonly const 区别

c# readonly const 区别

 

Const   静态的常量。

Readonly

final java 一样概念

静态的常量。


常量定义:在编译时。运行时不可以修改。
必须定义成:成员变量。




常量必须是
integral 完整类型type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string),an enumeration, or a reference to null.



其实就是基本类型 ==java 





Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure. 

  
常量 定义后就和 static 静态变量一样用。不需要static 关键字。

Constants are accessed as if they were static fields, although they cannot use the static keyword.

常量可以标记的前缀:
public, private, protected, internal, or protected internal.


Constants can be marked as public, private, protected, internal, or protected internal.

类名.常量


To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

动静态 都可以。

Class Instance 变量。的属性是可以修改的

Struct 的不是不可以 修改他的属性的。

readonly字段的赋值只能作为字段声明的组成部分出现,或在同一类中的实例构造函数静态构造函数中出现。


一个只读成员,表现出 不可以被修改。
只读成员, 初始化 在运行时。。。

可以初始化 在  定义 或者 构造




public class MyClass
            {
            public readonly double PI = 3.14159;
            }

or

public class MyClass
            {
            public readonly double PI;
             
            public MyClass()
            {
            PI = 3.14159;
            }
            }

注意
 只读成员  不是 隐式的静态,但是可以用static 修饰。

readonly 关键字 可以用 复杂类型,可以用new 关键子 初始化。


readonly 不能是 enu 枚举类型。

    const string sv = "abc" ;

    const float pii = 3.1415926f;

    const static string psss = "aaa"// 默认就是的static 并且这样不行

const string sss = null;


readonly string rdstr = System.Windows.Forms.Application.StartupPath + "aaa";

   Test() { // 构造函数。

    rdstr = "s" + sv;

    }

    private static readonly string path = System.Windows.Forms.Application.StartupPath + "aaa";

想赋值都不行。 只能用null

    const Test testt = new Test();

Test.cs(122,24): error CS0134:
        “Acme.Collections.Test.testt”的类型为“Acme.Collections.Test”。只能用
        null 对引用类型(字符串除外)的常量进行初始化


        Console.WriteLine( new Test().rdstr);  

        /*

         Test.cs(142,27): error CS0120:

        非静态的字段、方法或属性“Acme.Collections.Test.rdstr”要求对象引用

         */

        Console.WriteLine(path);



static 变量

static 关键字修饰。
被访问 不是在 实例创建时候。
静态方法和属性访问 静态事件。

 means that the member is no longer tied to a specific object.?

The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.














*
需要注意的一个问题是:

对于一个 readonlyReference类型,只是被限定不能进行赋值(写)操作而已。而对其成员的读写仍然是不受限制的。

public static readonly Class1 my = new Class1();

my.SomeProperty = 10;//
正常
my = new Class1(); //出错,该对象是只读的

但是,如果上例中的 Class1不是一个 Class而是一个 struct,那么后面的两个语句就都会出错。

static readonly:

Java 中 static是当载入一个类时执行一次的。

C#中是怎么执行的,我没有查到。很奇怪几乎每本java的书都会说static的问题,C#的往往只说怎么用,但是应该是在main函数调用之前初始化,所以static readonly也是运行时的,可以用变量付值,如:

private static readonly string path = System.Windows.Forms.Application.StartupPath + “aaa”;


引用下文
http://dev.csdn.net/develop/article/82/82998.shtm










http://en.csharp-online.net/const,_static_and_readonly

const, static and readonly

From C# Online.NET (CSharp-Online.NET)—your free C# and .NET encyclopedia


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

  • Manage data
    • Value types
    • Reference types
      • Declaring Classes
      • Nested Classes
      • Class Members
      • Constructors, Destructors
      • Copy Constructors
      • Fields and Properties
      • Interfaces, Abstract Classes
      • const, static, readonly
    • Attributes
    • Generic types
    • Exception classes
    • Boxing, Unboxing
    • TypeForwardedTo
    • Value vs Reference
  • Manage collections
  • Generic collections
  • Specialized collections
  • Implement interfaces
  • Events and delegates

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents

[hide]
  • 1 const vs. readonly
    • 1.1 const
    • 1.2 readonly
  • 2 static
  • 3 MSDN references


Within a class, const, static and readonly members are special in comparison to the other modifiers.

[ edit]

const vs. readonly

const and readonly perform a similar function on data members, but they have a few important differences.


[ edit]

const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;

public class MyClass
{
public const double PI = 3.14159;
}

PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.

Constants are accessed as if they were static fields, although they cannot use the static keyword.

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

[ edit]

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:

public class MyClass
{
public readonly double PI = 3.14159;
}

or

public class MyClass
{
public readonly double PI;
 
public MyClass()
{
PI = 3.14159;
}
}

Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. A readonly field can also be used for runtime constants as in the following example:

public static readonly uint l1 = (uint)DateTime.Now.Ticks;

Notes

  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  • A readonly member can hold a complex object by using the new keyword at initialization.
  • readonly members cannot hold enumerations.


[ edit]

static

Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. For example:

public class Car
{
public static int NumberOfWheels = 4;
}

The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.

static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

int i = Car.NumberOfWheels;


[ edit]

MSDN references

  • Constants (C# Programming Guide)
  • const (C# Reference)
  • readonly (C# Reference)
  • static (C# Reference)
  • Static Classes and Static Class Members (C# Programming Guide)
Retrieved from " http://en.csharp-online.net/const%2C_static_and_readonly"


你可能感兴趣的:(c# readonly const 区别)