C# 枚举与结构

来源:互联网 发布:udp端口命令 编辑:程序博客网 时间:2024/06/04 18:47

枚举

enum EmpType : byte  //默认为int型,部署在低内存设备中可以考虑修改存储的类型

        {
            Manager,            //  = 0
            Grunt,              //  = 1
            Contractor,         //  = 2
            VicePresident,      //  = 3
            Other = 100         // = 100 ,枚举不一定连续,也不需要唯一值
        }
        //枚举类型作为参数
        private void EnumFun(EmpType enums)
        {          
            //枚举
            switch (enums)
            {
                case EmpType.Other:
                    {
                        EmpType a = EmpType.Grunt;  //枚举类型赋值
                        a.ToString();  //ToString()返回当前枚举变量的字符串名,这里为 "Grunt"
                        byte s = (byte)a;  //获取枚举变量的值,只需根据底层存储类型对枚举变量进行强制类型转换。这里为1
                    }break;
                case EmpType.Grunt:
                    {
                        EmpType emp = EmpType.Contractor;
                        Type t = Enum.GetUnderlyingType(emp.GetType());  //返回保存枚举类型值的类型,当前为System.Byte
                    }break;
                case EmpType.Manager:
                    {
                        
                    } break;
            }

        }

结构

 struct StructTest
        {
            public int x;
            public int y;
           
            public StructTest(int x,int y)  //结构的构造函数
            {
                this.x = x;
                this.y = y;
            }
            public void Increment()
            {
                x++;
                y++;
            }
        }
        private void StructFun()
        { 
            //创建结构变量
            StructTest test1;
            test1.x = 1;
            test1.y = 2;
            test1.Increment();  //在使用两个字段之前,必须都要赋值


            StructTest test2 = new StructTest();  //默认构造,会给x,y赋默认值
            test2.Increment();


            StructTest test3 = new StructTest(3, 3);
            test3.Increment();
        }


值类型与引用类型
        当值类型包含了引用类型,在赋值的时候将产生一个引用的副本。这样就有两个独立的结构
         ,每一个结构包含指向内存中同一个对象的引用(浅复制),需要深复制,需要实现ICloneable接口
       
           .Net 2.0 发布后,引入了可空数据类型
         int? x = 10;  //这里的?实际上是System.Nullable<T>结构类型实例的简写。可通过HasValue属性或操作符!= 判断,一个可空变量是否确实被赋予了一个null值。
         
        


0 0
原创粉丝点击