C# 2012 step by step 学习笔记8 CHAPTER 9 使用枚举和结构创建值类型

本章内容

  1. 声明一个枚举类型
  2. 创建并使用一个枚举类型
  3. 声明一个结构类型
  4. 创建并使用一个结构类型
  5. 解释结构和类之间行为的区别

声明一个枚举

        enum Season { Spring, Summer, Fall, Winter }

使用枚举


        You can assign a value that is defined by the enumeration only to an enumeration variable.

        Note:As you can with all value types, you can create a nullable version of an enumeration variable by using the ?

modifier. You can then assign the null value, as well the values defined by the enumeration, to
the variable: Season?

colorful = null;

        All enumeration literal names are scoped by their enumeration type. This is useful because it allows different enumerations to coincidentally contain literals with the same name.
        Many of the standard operators you can use on integer variables can also be used on enumeration variables (except the bitwise and shift operators, which are covered in Chapter 16, “Using Indexers”). For example, you can compare two enumeration
variables of the same type for equality by using the equality operator (==), and you can even perform arithmetic on an enumeration variable (although the result might not always be meaningful!).

Choosing enumeration Literal Values

        Internally, an enumeration type associates an integer value with each element of the enumeration. By default, the numbering starts at 0 for the first element and goes up in steps of 1.
        If you prefer, you can associate a specific integer constant (such as 1) with an enumeration literal (such as Spring), as in the following example: 
enum Season { Spring = 1, Summer, Fall, Winter }
        Important:The integer value with which you initialize an enumeration literal must be a compile-time constant value (such as 1).
        the underlying values of Spring, Summer, Fall, and Winter are now 1, 2, 3, and 4.
        You are allowed to give more than one enumeration literal the same underlying value.
enum Season { Spring, Summer, Fall, Autumn = Fall, Winter }

Choosing an enumeration’s Underlying type

        When you declare an enumeration, the enumeration literals are given values of type int. You can also choose to base your enumeration on a different underlying integer type. For example, to declare that Season’s underlying type is a short rather
than an int, you can write this:

enum Season : short { Spring, Summer, Fall, Winter }

        The main reason for doing this is to save memory; an int occupies more memory than a short, and if you do not need the entire range of values available to an int, using a smaller data type can make sense.
        You can base an enumeration on any of the eight integer types: byte, sbyte, short, ushort, int, uint,long, or ulong. The values of all the enumeration literals must fit inside the range of the chosen base type. For example, if you base an enumeration
on the byte data type, you can have a maximum of 256 literals (starting at 0).

Working with Structures

         In some cases, the class can contain so little data that the overhead of managing the heap becomes disproportionate. In these cases, it is better to define the type as a structure. A structure is a value type. Because structures are stored on
the stack, as long as the structure is reasonably small, the memory management overhead is often reduced.
        Like a class, a structure can have its own fields, methods, and (with one important exception discussed later in this chapter) constructors.

Common Structure types

        In C#, the primitive numeric types int, long, and float are aliases for the structures System.Int32, System.Int64, and System.Single, respectively. These structures have fields and methods, and you can actually call methods on variables and literals
of these types. 

Declaring a Structure

        To declare your own structure type, you use the struct keyword followed by the name of the type, followed by the body of the structure between opening and closing braces. Syntactically, the process is similar to declaring a class.

        As with classes, making the fields of a structure public is not advisable in most cases; there is no way to control the values held in public fields.A better idea is to make the fields private and provide your structure with constructors and methods
to initialize and manipulate these fields。

        Note By default, you cannot use many of the common operators on your own structure types. For example, you cannot use operators such as the equality operator (==) and the inequality operator (!=) on your own structure type variables. However, you
can use the builtin Equals() method exposed by all structures to compare them, and you can also explicitly declare and implement operators for your own structure types. The syntax for doing this is covered in Chapter 22, “Operator Overloading.”
tip Use structures to implement simple concepts whose main feature is their value rather than the functionality that they provide.

Understanding Structure and Class Differences

        You can’t declare a default constructor (a constructor with no parameters) for a structure.

        The reason you can’t declare your own default constructor for a structure is that the compiler always generates one.
        You can initialize fields to different values by providing a nondefault constructor. However,when you do this, your nondefault constructor must explicitly initialize all fields in your structure; the default initialization no longer occurs. If
you fail to do this, you’ll get a compile-time error.
        In a class, you can initialize instance fields at their point of declaration. In a structure, you cannot.


        There are other differences between classes and structures concerning inheritance. These differences are covered in Chapter 12, “Working with Inheritance.”

Declaring Structure Variables

        Note As with enumerations, you can create a nullable version of a structure variable by using the ? modifier. You can then assign the null value to the variable:

Time? currentTime = null;

Understanding Structure Initialization

Time now = new Time();

        However, because structures are value types, you can also create structure variables without calling a constructor

        Note that in both cases, the Time variable is created on the stack.
        If you’ve written your own structure constructor, you can also use that to initialize a structure variable.

Time now = new Time(12, 30);

Copying Structure Variables

        You’re allowed to initialize or assign one structure variable to another structure variable, but only if the structure variable on the right side is completely initialized (that is, if all its fields are populated with valid data rather than undefined
values).
Date now = new Date();

Date copy = now;

         When you copy a structure variable, each field on the left side is set directly from the corresponding field on the right side. This copying is done as a fast, single operation that copies the contents of the entire structure and that never throws
an exception.
Note C++ programmers should note that this copy behavior cannot be customized.

C# step by step 学习笔记8 CHAPTER 9 使用枚举和结构创建值类型的更多相关文章

  1. C#学习笔记10:Try-catch的用法和引用类型、值类型整理

    Try-Catch: 将可能发生异常的代码放到try中,在catch中进行捕获. 如果try中有一行代码发生了异常,那么这行代码后面的代码不会再被执行了. Try写完了以后,紧接着就要写Catch   ...

  2. Net基础篇_学习笔记_第十二天_面向对象继承(命名空间 、值类型和引用类型)

    命名空间可以认为类是属于命名空间的. 解决类的重名问题,可以看做类的“文件夹”如果在当前项目中没有这个类的命名空间,需要我们手动的导入这个类所在的命名空间.1).用鼠标去点2).alt+shift+F ...

  3. 【Unity Shaders】学习笔记——SurfaceShader(二)两个结构体和CG类型

    [Unity Shaders]学习笔记——SurfaceShader(二)两个结构体和CG类型 转载请注明出处:http://www.cnblogs.com/-867259206/p/5596698. ...

  4. cocos2d-x入门学习笔记,主要介绍cocos2d-x的基本结构,并且介绍引擎自带的示例

    cocos2d-x 3.0 制作横版格斗游戏 http://philon.cn/post/cocos2d-x-3.0-zhi-zuo-heng-ban-ge-dou-you-xi http://blo ...

  5. C语言学习笔记10-结构体、枚举、联合体

    C语言学习笔记10-结构体.枚举.联合体    待传

  6. Swift学习笔记(9):枚举

    目录: 基本语法 关联值 原始值 枚举为一组相关的值定义了一个共同的类型. ・可以给枚举成员指定原始值类型:字符串,字符,整型值或浮点数等 ・枚举成员可以指定任意类型的关联值存储到枚举成员中 ・枚举可 ...

  7. Python学习笔记(1):列表元组结构

    Python的列表元组功能强大,令人印象深刻.一是非常灵活,二是便于集体操作.特别是以元组作为列表项的结构,和数据访问的结果能够对应起来,和习惯的二维表理解上也一致,有很多的用途. 以学习笔记(3)中 ...

  8. [原创]java WEB学习笔记44:Filter 简介,模型,创建,工作原理,相关API,过滤器的部署及映射的方式,Demo

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  9. WebGL three.js学习笔记 法向量网格材质MeshNormalMaterial的介绍和创建360度全景天空盒的方法

    WebGL学习----Three.js学习笔记(5) 点击查看demo演示 Demo地址:https://nsytsqdtn.github.io/demo/360/360 简单网格材质 MeshNor ...

随机推荐

  1. 数据结构之--图(Graphics)

    1.1:图的定义和术语   图是一种比线性表和树更为复杂的数据结构.在线性表中,数据元素之间仅有线性关系,每个元素仅有一个直接前驱和一个直接后继:在树形结构中,数据元素之间有着明显的层次关系,并且每一 ...

  2. myeclipse 改变模版

    一.修改Servlet的默认模板代码 使用MyEclipse创建Servlet时,根据默认的Servlet模板生成的Servlet代码如下: 1 package gacl.servlet.study; ...

  3. js中的this关键字

    this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用,下面分四种情况,详细讨论this的用法 this是Javascript语言的一个关键字. 它 ...

  4. cobbler安装配置(二)

    安装环境: 操作系统:CentOS 6.5 x86_64测试机器ip:192.168.0.1 关闭防火墙.selinux:service iptables stop && chkcon ...

  5. zoj 2679 Old Bill

    Old Bill Time Limit: 2 Seconds      Memory Limit: 65536 KB Among grandfather��s papers a bill was fo ...

  6. oracle11g rac 个性归档模式

    关闭数据库并将一节点启动到mount状态 [root@QSZAAS-XYORC02 ~]# su - grid[grid@QSZAAS-XYORC02 ~]$ srvctl stop database ...

  7. 【容器人必看】你一定要来 ECUG Con 2018 的三个理由!

    引领国内云领域风向的高端峰会 ECUG Con 2018,即将在 12 月 22-23 日 深圳南山 全新启程!如果你的工作和容器内容相关联,如果你的兴趣和容器技术有交集,如果你是「容器人」,那么这就 ...

  8. BZOJ 3611 [Heoi2014]大工程 ——虚树

    虚树第二题.... 同BZOJ2286 #include <map> #include <cmath> #include <queue> #include < ...

  9. C 语言中的 fgets()

    转自:http://blog.csdn.net/daiyutage/article/details/8540932 原型: char *  fgets(char * s, int n,FILE *st ...

  10. charts jupyter notebook 画简单的柱状图

    数据库是mongdb 数据是58同城上发的转手记录 一 为了保证数据安全,对需要进行处理的数据进行拷贝. > db.createCollection('test') { } > show ...