更新时间:2022-09-11 12:15:02
Features:
Examples:
using System;
public class Order
{
public Order()
{
Guid guid = Guid.NewGuid();
ID = guid.ToString("D");
}
// 对于每一份订单,其订单序号都是实时确定的常量。
public readonly string ID;
public override string ToString()
{
return "Order ID: " + ID;
}
}
Explaintion:
- 如果结合数据库使用,ID field通常都会都会与某个表的主健(primary key)关联起来,如Orders表的OrderID。
- 数据库的主健通常采用以下三种方式:
- 自动递增值。你可以通过把DataColumn.AutoIncrement设定为true值来激活自动递增特性。
- 唯一名称。这个是使用自己定义的算法来生成一个唯一序列号。
- GUID(全局唯一标识符)。你可以通过System.Guid结构来生成GUID,如上例。
using System;
class Customer
{
public Customer(string name, int kind)
{
m_Name = name;
m_Kind = kind;
}
public const int NORMAL = 0;
public const int VIP = 1;
public const int SUPER_VIP = 2;
private string m_Name;
public string Name
{
get { return m_Name; }
}
private readonly int m_Kind;
public int Kind
{
get { return m_Kind; }
}
public override string ToString()
{
if(m_Kind == SUPER_VIP)
return "Name: " + m_Name + "[SuperVip]";
else if(m_Kind == VIP)
return "Name: " + m_Name + "[Vip]";
else
return "Name: " + m_Name + "[Normal]";
}
}
Remarks:
Using directives#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ConstantLab
{
class Program
{
static void Main(string[] args)
{
Constant c = new Constant(3);
Console.WriteLine("ConstInt = " + Constant.ConstInt.ToString());
Console.WriteLine("ReadonlyInt = " + c.ReadonlyInt.ToString());
Console.WriteLine("InstantReadonlyInt = " + c.InstantReadonlyInt.ToString());
Console.WriteLine("StaticReadonlyInt = " + Constant.StaticReadonlyInt.ToString());
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
class Constant
{
public Constant(int instantReadonlyInt)
{
InstantReadonlyInt = instantReadonlyInt;
}
public const int ConstInt = 0;
public readonly int ReadonlyInt = 1;
public readonly int InstantReadonlyInt;
public static readonly int StaticReadonlyInt = 4;
}
}