常量是指在程序运行过程中不可改变的。通过关键字const来声明变量。
例如
const double PI=3.14159265;
定义常量时,表达式中的运算符对象只允许出现常量,不能有变量存在。
int a=20;
const int b=30;
const int c=b+45;//correct
const int d=a+45;//wrong
c=15;//wrong,cant change the value of constant
声明变量的作用之一是分配内存空间。
例如
double total=34.3D;
int x=10,y=2;
变量命名规范:
多数变量命名采用Camel命名方法,即stuName、productId等。
所有值类型和引用类型都由object的基本类发展而来。在C#中还可以通过隐式转换(不会造成数据丢失)或显示转换(数据丢失或精度降低)。
装箱:值类型到object类型或此值类型所实现的任何接口类型的隐式转换
拆箱:object类型到值类型或从接口类型到实现该接口的值类型的显示转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo2_BoxingExample
{
class Program
{
static void Main(string[] args)
{
int i = 20;
object obj = i; //隐式装箱
Object obj2 = (object)i; //显示装箱
if(obj is int)
{
Console.WriteLine("ok");
}
Console.WriteLine(obj);
Console.WriteLine(obj2);
Console.WriteLine(obj.GetType());
Console.WriteLine(obj2.GetType());
Console.ReadKey();
}
}
}
int i=10;
object obj=i; //隐式装箱
int j=(int)obj; //拆箱
隐式转换是系统默认的,不需加以声明就可以进行转换。
int a=10;
long b=a;
double c=a;
显示转换又称强制类型转换。
(int)5.17;
string → int:int.Parse();
→string:ToString;
同时,也可以使用System.Convert达到目的,Convert.ToInt32、Convert.ToString。
DateTime是用来表示时间和处理时间的类型,属于结构类型。
例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo2_DateTime
{
class Program
{
static void Main(string[] args)
{
DateTime dt;
Console.WriteLine("please input date:(2000-01-01或2000/01/01)");
dt = DateTime.Parse(Console.ReadLine());//日期字符串→日期格式类型
//DayOfWeek返回的是0 1 2 3 4 5 6,对应日 一...
string str = "日一二三四五六".Substring((int)dt.DayOfWeek, 1);
Console.WriteLine("{0}年{1}月{0}日是星期{3}", dt.Year, dt.Month, dt.Day, str);
Console.WriteLine("{0}年{1}月{0}日是这一年的第{3}天", dt.Year, dt.Month, dt.Day, dt.DayOfYear);
Console.WriteLine("{0}是星期{1}", dt.ToShortDateString(),str);
Console.WriteLine("{0}年是这一年的第{1}天", dt.ToLongDateString(),dt.DayOfYear);
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo2_DateTime
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("现在时间:{0}", DateTime.Now.ToString("yyyy-M-d H:m:s"));
Console.WriteLine("现在时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine("现在时间:{0}", DateTime.Now.ToString("yyyy-MM-dd"));
Console.WriteLine("短日期字符串:{0}", DateTime.Now.Date.ToShortDateString());
Console.WriteLine("长日期字符串:{0}", DateTime.Now.Date.ToLongDateString());
Console.ReadKey();
}
}
}