文件名称:结构示例-eda技术实用教程 vhdl版(第四版) 潘松 科学出版社
文件大小:4.12MB
文件格式:PDF
更新时间:2024-07-07 04:50:10
C#
11.4 结构示例 下面的内容展示了关于应用 struct 类型的两个重要示例,它们各自创建一个类型,这些类型使用起来 就像 C# 语言的预定义类型,但具有修改了的语义。 11.4.1 数据库整数类型 下面的 DBInt 结构实现了一个整数类型,它可以表示 int 类型的值的完整集合,再加上一个用于表示 未知值的附加状态。具有这些特征的类型常用在数据库中。 using System; public struct DBInt { // The Null member represents an unknown DBInt value. public static readonly DBInt Null = new DBInt(); // When the defined field is true, this DBInt represents a known value // which is stored in the value field. When the defined field is false, // this DBInt represents an unknown value, and the value field is 0. int value; bool defined; // Private instance constructor. Creates a DBInt with a known value. DBInt(int value) { this.value = value; this.defined = true; } // The IsNull property is true if this DBInt represents an unknown value. public bool IsNull { get { return !defined; } } // The Value property is the known value of this DBInt, or 0 if this // DBInt represents an unknown value. public int Value { get { return value; } } // Implicit conversion from int to DBInt. public static implicit operator DBInt(int x) { return new DBInt(x); } // Explicit conversion from DBInt to int. Throws an exception if the // given DBInt represents an unknown value. public static explicit operator int(DBInt x) { if (!x.defined) throw new InvalidOperationException(); return x.value; } public static DBInt operator +(DBInt x) { return x; } public static DBInt operator -(DBInt x) { return x.defined ? -x.value : Null; } public static DBInt operator +(DBInt x, DBInt y) { return x.defined && y.defined? x.value + y.value: Null; } public static DBInt operator -(DBInt x, DBInt y) { return x.defined && y.defined? x.value - y.value: Null; }