C# study notes structure, enumeration

structure

Structure (struct) is a data structure that encapsulates data and functions. Compared with class (class), the biggest difference is that structure is a value type, while a class is a reference type. The general structure is used for objects that are simpler than classes.

Structure declaration and use

Like classes, structures can contain various members, such as: constructors, constants, fields, methods, properties, indexers, events, operators, and nested value types. At the same time, the structure can also implement interfaces. The type declaration format of the structure is as follows:

struct 结构名 [:接口名]
{
    
    
	...
}

structThe structure type is suitable for representing simple data structures such as points, matrices, and colors. E.g:

struct Point 
{
    
    
	public double x, y;
    public Point (double x, double y) {
    
    
	this.x = x;
	this.y = y;
    }
	public double R () {
    
    
        return Math.Sqrt (x * x + y * y);
	}
}

class Program
{
    
    
	static void Main (string[] args) {
    
    
		Point[] points = new Point[100];
            for (int i = 0; i < points.Length; i++) {
    
    
                points[i] = new Point (i, i * i);   // 数值的copy
                Console.WriteLine (points[i].R ());
            }
	}
}

Using structures instead of classes for Point can make a big difference in the storage location of the members. In the above program, an array of 100 elements is created and initialized. If Pointimplemented with a class, the program will take up 101 discrete objects, one for the array, and the other 100 for each element. However, if the structure is used to implement Point, the program will only occupy one object, that is, one array, which is more efficient.

Restrictions on the use of the structure

The structure does not support inheritance during use. When using the structure, you need to pay attention to the following points:

  • Structures cannot be inherited from other types, only from interfaces. But all structures are implicitly inherited Object.
  • The structure cannot include parameterless construction methods. It is believed that any configuration, the system automatically provides a no-argument constructor, the constructor automatically assigned an initial value for each field ( 0, false, nulletc.).
  • If there is a construction method, in the construction method, you must explicitly assign a value to each field so that each field is determined.
  • When each field is defined, no initial value can be given. But the constconstant must be assigned a value.
  • The structure cannot have a destructor method.
  • Structure members cannot be modified by protected, as they protectedare related to inheritance.
  • Variable structure type can not be used ==to compare determined, unless the operator being defined ==.

When using a structure, the instantiation of the structure can be done without using newoperators. If not used new, then all of the fields are the default initial value ( 0, false, nulletc.). If used new, you can call the corresponding construction method. In short, the instantiation of the structure can be used newor not new, and the instantiation of the class must be used new.

enumerate

Enumeration (enum) is used in situations where there are multiple choices. Enumeration types provide a type name for a set of symbolic constants. Each member in the enumeration is actually a symbolic constant. E.g:

enum LightColor
{
    
    
	Red, Yellow, Green
}

It declares an enumerated type Colorthat represents 3 possibilities: Red, Yellow, Green. Here are three values are actually three integers 0, , 1, 2but compared with integer, enum make better readability, and easy to detect errors.

Enumeration declaration

Declare enumeration types using keywords enum. The basic format of the declaration is as follows:

enum 枚举名 [:基本类型名]
{
    
    
	枚举成员 [ = 常数表达式],
	...
}

Each enumeration type has a corresponding integer type, called the underlying type of the enumeration type. A statement can be enumerated explicitly declared byte, sbyte, short, ushort, int, uint, longor ulonga basic types. Note that char cannot be used as a basic type. If the basic type is not declared, the default is int.
Implicit assignment determines the value according to the following rules:

enum Color
{
    
    
	Red,
	Green = 10,
	Blue,
	Max = Blue
}

Where Redthe value is 0, Greenthe value is 10, Bluethe value is 11, and Maxthe value is 11.
Modifiers cannot be explicitly used in front of enumeration members. Each enumeration member is implicitly const, and its value cannot be changed; each member is implicitly publictrue, and its access control is unrestricted; each member is implicitly statictrue, and the enumeration type name is used directly for access . E.g:

enum LightColor
{
    
    
	Red, Yellow, Green
}
class TrafficLight
{
    
    
	public static void WhatInfo(LightColor color) {
    
    
		switch (color) {
    
    
			case LightColor.Red:
			Console.WriteLine("Stop!");
			break;
			case LightColor.Yellow:
			Console.WriteLine("Warning!");
			break;
			case LightColor.Green:
			Console.WriteLine("Go!");
			break;
			default:
			break;
		}
	}
	public static LightColor GetRandomColor() {
    
    
		Random rng = new Random();
		int num = rng.Next (3);
		return (LightColor)num;
	}
}
class Test
{
    
    
	static void Main (string[] args) {
    
    
		LightColor c = TrafficLight.GetRandomColor();
		Console.WriteLine(c.ToString());
		TrafficLight.WhatInfo(c);
	}
}

Enumeration operations

Each enumerated type is automatically System.Enumderived from the class . Therefore, Enumthe methods and properties of the class can be used on the value of an enumerated type. For enumerated type, the operator can use most of the integer type can be used, comprising: a ==, !=, <, >, <=, >=, +, -, ^, &, |, ~, ++, --, sizeof.
The conversion between enumeration type and integer type should use coercive type conversion. A special case is that the constant 0 can be implicitly converted to any enumerated type.
Enumeration types can also be converted to and from strings. The ToString()method of the enumeration type can get a string, which is the name of the corresponding enumeration member, as used in the above example Console.WriteLine(c.ToString());.
System.EnumThe Parse()method can convert the enumeration constant string into an equivalent enumeration object. Parse()The method format is as follows:

	public static object Parse(Type, string);

E.g:

	Color c = (Color)Enum.Parse(typedef(Color), "Red");

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114006995
Recommended