Ta có thể khai báo như sau:
const int x = 0;
public const double gravitationalConstant = 6.673e-11;
private const string productName = "Visual C#";
public const double x = 1.0, y = 2.0, z = 3.0;
Và mã ví dụ sau:
public class ConstTest
{
class SampleClass
{
public int x;
public int y;
public const int c1 = 5;
public const int c2 = c1 + 5;
public SampleClass(int p1, int p2)
{
x = p1;
y = p2;
}
}
static void Main()
{
SampleClass mC = new SampleClass(11, 22);
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
Console.WriteLine("c1 = {0}, c2 = {1}",
SampleClass.c1, SampleClass.c2 );
}
}
/* Output
x = 11, y = 22
c1 = 5, c2 = 10
*/
----------Với từ khóa Readonly có một chút khác biệt với const một xíu.
cơ bản bạn cũng không thể thay thế một giá trị sử dụng readonly y chang const tuy nhiên chúng có thể thay đổi thông qua constructor.
Khi ta gán giá trị thông qua constructor và gán cho các giá trị readonly thì có thể kiểm soát chúng.
Xem mã ví dụ dưới đây
public class ReadOnlyTest
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
// Một Constructor có tên giống với class chứa nó. mục đích khởi tạo
public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
// Thông qua 1 constructor này và gán các giá trị khai báo
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
static void Main()
{
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
p2.x = 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}
/*
Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
*/
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Mã code:
using System;
namespace TestChar
{
public class Program
{
class RO
{
public readonly int A = 24;
public readonly int B=26;
public RO()
{
B = 25;
}
}
static void Main(string[] args)
{
var ce = new RO();
Console.WriteLine(ce.B);
Console.ReadLine();
//out: B= 25;
}
}
}
012. Keyword [const] [readonly]
Related Tags :WritingObsolete
No comments:
Post a Comment
Commets Download Photoshop Actions, Lightroom Presets, PSD Template, Mockups, Stocks, Vectors, Fonts. Download free