常量
定义常量时,在数据类型前添加 const。
常量是定义后不可以被改变的值,变量是定义后可以改变的值。
枚举类型
// enum 声明枚举关键字
// 枚举名: 要符合Pascal 命名规范
// 声明
public enum Name
{
value1,
value2,
....
}
// 使用
Name name = Name.value1;
以下是枚举类型使用和转换的例子
namespace DataType {
public enum Seasons
{
Spring,
Summer,
Autumn,
Winter
}
public enum Months
{
January = 1,
March = 3,
April,
July = 7,
August,
September,
}
class Program {
public static Seasons season;
public static void Main(string[] args)
{
season = Seasons.Summer;
Console.WriteLine(season);
Console.WriteLine((int)season);
Console.WriteLine("{0} , {1}", (int)Months.September, Months.September);
Console.WriteLine("{0} , {1}", (int)Months.January, Months.January);
Console.WriteLine((Months)3);
//string to enum
// if s is not in Seasons, will throw exception
string s = "0";
Console.WriteLine((Seasons)Enum.Parse(typeof(Seasons), s));
Console.WriteLine(Enum.Parse(typeof(Seasons), s));
//bool test = Enum.TryParse(typeof(Seasons), s, out Season.season);
}
}
}
结构体
namespace DataType
{
public enum Gender
{
M, //male
F //female
}
// 在class外,需要给person定义为public
// 字段之前要加一个下划线,以区分字段和变量
public struct Person
{
public string _name;
public Gender _gender;
public int _age;
};
public struct Person1
{
string _name;
char _gender;
int _age;
};
class StructExample
{
static void Main(string[] args)
{
Person person1;
Person person2 = new Person();
Person1 person11 = new Person1();
person1._name = "James";
person1._gender = Gender.M;
person2._name = "Bob";
person2._gender = Gender.F;
}
}
}