C# 数据类型

常量

定义常量时,在数据类型前添加 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;  
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anunnaki_IO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值