1 泛型结构
结构和类同属于复合类型,可以有字段成员、方法成员和嵌套成员。同样,可以通过引入类型参数来定义泛型结构。泛型类的定义规则,包括类型限制、继承定义、构造类型的指定等,同样可以应用于泛型结构。二者之间的本质区别仍在于引用类型和值类型之间的差别。
将MoreGenericSample程序进行修改,实现的功能类似。不同的是泛型类Relation<L,R>维护的只是一个数组,数组元素的类型则是泛型结构。
class GenericStructSample { static void Main(string[] args) { Relation<int, double> sinTable = new Relation<int, double>(180); for (int i = 0; i < 180; i++) { sinTable.SetLeft(i,i); sinTable.SetRight(i,Math.Sin(Math.PI * i / 180)); } //求正弦函数 Console.WriteLine("请输入度数(0~179之间):"); int x = int.Parse(Console.ReadLine()); double y = sinTable.GetRight(x); Console.WriteLine("Sin({0}度)={1}", x, y); //求反正弦函数 Console.WriteLine("请输入一个实数(0~1之间):"); double r = double.Parse(Console.ReadLine()); int pos; for (pos = 0; pos < sinTable.Length; pos++) { if (Math.Abs(r-sinTable.GetRight(pos)) < 0.005) { break; } } if (pos == sinTable.Length) Console.WriteLine("没有找到指定的反正弦值"); else Console.WriteLine("arcsin({0})={1}度", r, sinTable.GetLeft(pos)); } } /// <summary> /// 泛型结构:关联元素RelationElement /// </summary> public struct RelationElement<L,R> { //字段 private L m_left; private R m_right; //属性 public L Left { get { return m_left; } set { m_left = value; } } public R Right { get { return m_right; } set { m_right = value; } } //构造函数 public RelationElement(L left, R right) { m_left = left; m_right = right; } } /// <summary> /// 泛型类:关联Relation /// </summary> public class Relation<L,R> { //字段 public RelationElement<L, R>[] m_list; //属性 public int Length { get { return m_list.Length; } } //构造函数 public Relation(int iLength) { m_list = new RelationElement<L, R>[iLength]; } //方法 public L GetLeft(int index) { return m_list[index].Left; } public R GetRight(int index) { return m_list[index].Right; } public void SetLeft(int index,L left) { m_list[index].Left=left; } public void SetRight(int index,R right) { m_list[index].Right = right; } public int FindLeft(L left) { for (int i = 0; i < Length; i++) { if (m_list[i].Equals(left)) return i; } return -1; } public int FindRight(R right) { for (int i = 0; i < Length; i++) { if (m_list[i].Equals(right)) return i; } return -1; } }