C#常量和编程实例

C#常量

一 

常量是在编译时已知并在程序的生存期内不发生更改的不可变值。 常量使用 const 修饰符进行声明。 只有 C# 内置类型(System.Object 除外)可以声明为 const。 
用户定义的类型(包括类、结构和数组)不能为 const。 请使用 readonly 修饰符创建在运行时初始化一次即不可再更改的类、结构或数组。
C# 不支持 const 方法、属性或事件。
可以使用枚举类型为整数内置类型(例如 int、uint、long 等等)定义命名常量。 参见 enum。
常量必须在声明时初始化。 例如:

class Calendar1
{
    public const int months = 12;
}


当编译器遇到 C# 源代码(例如 months)中的常量修饰符时,将直接把文本值替换到它生成的中间语言 (IL) 代码中。 因为在运行时没有与常量关联的变量地址,所以 const 字段不能通过引用传递,并且不能在表达式中作为左值出现。

当引用在其他代码如 DLL 中定义的常量值时应十分谨慎。 如果新版本的 DLL 为常量定义了新的值,程序仍将保留旧的文本值,直到针对新版本重新编译程序。

可以同时声明多个相同类型的常量,例如:

class Calendar2
{
    const int months = 12, weeks = 52, days = 365;
}

如果不会造成循环引用,用于初始化一个常量的表达式可以引用另一个常量。 例如:

class Calendar3
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

常量可标记为 public、private、protected、internal 或 protectedinternal。 这些访问修饰符定义类的用户访问该常量的方式。 
因为常量值对该类型的所有实例是相同的,所以常量被当作 static 字段一样访问。 不使用 static 关键字声明常量。 未包含在定义常量的类中的表达式必须使用类名、一个句点和常量名来访问该常量。 例如:
int birthstones = Calendar.months;

2
在程序中使用常量至少有3个好处:
a.常量用易于理解的清楚的名称替代了含义不明确的数字或字符串,使程序更易于阅读。
b.常量使程序更易于修改。例如,在C#程序中有一个SalesTax常量,该常量的值为6%。如果以后销售税率发生变化,把新值赋给这个常量,就可以修改所有的税款计算结果,而不必查找整个程序,修改税率为0.06的每个项。
C.常量更容易避免程序出现错误。如果要把另一个值赋给程序中的一个常量,而该常量已经有了一个值,编译器就会报告错误。

在C#中定义常量的方式有两种,一种叫做静态常量(Compile-time constant),另一种叫做动态常量(Runtime constant)。前者用“const”来定义,后者用“readonly”来定义。

3
有const 的都是常量
const int a=3; 就是常量 
常量赋值后不可以修改。 常量 一般用于 经常使用的变量而且是全局的
常量是在编译时设置其值并且永远不能更改其值的字段。 

定义浮点型时,用float,不过后面要加个F,
float x = 1.2356f;
Console.Write(x);

字符常量是括在单引号里,例如,'x',且可存储在一个简单的字符类型变量中。一个字符常量可以是一个普通字符(例如 'x')、一个转义序列(例如 '\t')或者一个通用字符(例如 '\u02C0')。
在 C# 中有一些特定的字符,当它们的前面带有反斜杠时有特殊的意义,可用于表示换行符(\n)或制表符 tab(\t)。

二 编程实例
1
using System;

namespace DeclaringConstants
{
    class Program
    {
        static void Main(string[] args)
        {
            const double pi = 3.14159; // 常量声明
            double r;
            Console.WriteLine("输入半径: ");
            r = Convert.ToDouble(Console.ReadLine());
            double areaCircle = pi * r * r;
            Console.WriteLine("半径: {0}, 面积: {1}", r, areaCircle);
            
            Console.Write("按任意键继续 . . . ");
Console.ReadKey(true);
    }
}
}

2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace changliang
{
    public sealed class SomeLibraryType
    {
      public const Int32 MaxEntriesInList=50 ; 


        //可以同时声明多个常量
     public const Int32 month = 12, weeks = 52, days = 365;


        //如果不会造成循环引用,用于初始化一个常量的表达式可以引用另一个常量
     const double daysPerWeek = (double)days / weeks;
        const double daysPerMonth = (double)days / month;   
    }


class Program
    {
        static void Main(string[] args)
        {
            //这说明了常量的调用方式
       Console.WriteLine(SomeLibraryType.MaxEntriesInList);
             
            //不允许修改常量的值
       //常量的版本控制问题,只有重新编译,常量值才会获得新值,如果在运行时,如果一个程
       //序集要从另外1个程序集获得新值,那么不能使用常量,应该使用字段。
       //SomeLibraryType.MaxEntriesInList = 4;
       
       Console.Write("按任意键继续 . . . ");
Console.ReadKey(true);
        }
    }
}


using System;

static class Constants
{
    public const double Pi = 3.14159;
    public const int SpeedOfLight = 300000; // km per sec.


}
class Program
{
    static void Main()
    {
        double radius = 5.3;
        double area = Constants.Pi * (radius * radius);
        int secsFromSun = 149476000 / Constants.SpeedOfLight; // in km
        
        Console.Write(area);
        Console.Write("\n");
        Console.Write(secsFromSun);
        Console.Write("\n");
        
        Console.Write("按任意键继续 . . . ");
Console.ReadKey(true);
    }
}

4 转义字符常量示例
using System;

namespace EscapeChar
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello\tWorld\n\n");
            
            Console.Write("按任意键继续 . . . ");
    Console.ReadKey(true);
        }
    }

}

上述代码的运行截图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Example002-渐显的窗体 Example003-使程序始终在前面 Example004-将窗体编译成类库 Example005-继承窗体的设计 Example006-设计多边形窗体 Example007-用获取路径的方法得到圆形窗体 Example008-分割窗体 Example009-在菜单中加入图标 Example010-渐变的窗口背景 Example011-使用任务栏的状态区 Example012-在运行时更新状态栏信息 Example013-无标题窗体的拖动 Example014-设置应用程序的图标 Example015-共享菜单项 Example016-动态设置窗体的光标 Example017-自己绘制菜单 Example018-向窗体的系统菜单添加菜单项 namespace Example018_向窗体的系统菜单添加菜单项 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2}); this.menuItem1.Text = "File"; // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "Exit"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(292, 273); this.Menu = this.mainMenu1; this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr GetSystemMenu(IntPtr hwnd,bool bRevert); [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr AppendMenu(IntPtr hMenu,int wFlags,IntPtr wIDNewItem,string lpNewItem); const int MF_POPUP = 0x0010; const int MF_SEPARATOR = 0x0800; static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { IntPtr mnuSystem; mnuSystem=GetSystemMenu(this.Handle,false); AppendMenu(mnuSystem, MF_SEPARATOR, (IntPtr)0, ""); for(int i= 0;i<this.mainMenu1.MenuItems.Count;i++) { AppendMenu(mnuSystem,MF_POPUP,this.mainMenu1.MenuItems[i].Handle,this.mainMenu1.MenuItems[i].Text); } } private void menuItem2_Click(object sender, System.EventArgs e) { Application.Exit(); } } } namespace Example019_本地化Windows窗体_1_ { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // Thread.CurrentThread.CurrentUICulture=new CultureInfo("zh-cn"); InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.AccessibleDescription = ((string)(resources.GetObject("button1.AccessibleDescription"))); this.button1.AccessibleName = ((string)(resources.GetObject("button1.AccessibleName"))); this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("button1.Anchor"))); this.button1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("button1.BackgroundImage"))); this.button1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("button1.Dock"))); this.button1.Enabled = ((bool)(resources.GetObject("button1.Enabled"))); this.button1.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("button1.FlatStyle"))); this.button1.Font = ((System.Drawing.Font)(resources.GetObject("button1.Font"))); this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.ImageAlign"))); this.button1.ImageIndex = ((int)(resources.GetObject("button1.ImageIndex"))); this.button1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("button1.ImeMode"))); this.button1.Location = ((System.Drawing.Point)(resources.GetObject("button1.Location"))); this.button1.Name = "button1"; this.button1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("button1.RightToLeft"))); this.button1.Size = ((System.Drawing.Size)(resources.GetObject("button1.Size"))); this.button1.TabIndex = ((int)(resources.GetObject("button1.TabIndex"))); this.button1.Text = resources.GetString("button1.Text"); this.button1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.TextAlign"))); this.button1.Visible = ((bool)(resources.GetObject("button1.Visible"))); // // Form1 // this.AccessibleDescription = ((string)(resources.GetObject("$this.AccessibleDescription"))); this.AccessibleName = ((string)(resources.GetObject("$this.AccessibleName"))); this.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("$this.Anchor"))); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1}); this.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("$this.Dock"))); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "Form1"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Visible = ((bool)(resources.GetObject("$this.Visible"))); this.ResumeLayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值