visual C#(十七)泛型概述

参考书:《 visual C# 从入门到精通》
第三部分 用C#定义可扩展类型
第17章 泛型概述

17.1 Object 问题

可以用object;类型引用任何类型的值或者变量,所有引用类型都自动从object类继承。但实际我们用object的时候是很容易出错的。需要注意在必要的时候进行类型转换。

17.2 泛型解决方案

泛型和方法接受类型参数,他们指定了要操作的对象的类型。类型参数放到尖括号中来指定泛型类。

class Queue<T>{
    ...;
}

T为类型参数,作为占位符使用,会在编译时被真正的类型取代。如:

class Queue<T>{
    ...;
    private T[] data;
    ...;
    public Queue(){
        this.data=new T[DEFAULTQUEUESIZE];
    }
    public Queue(int size){
        ...;
        this.data=new T[size];
    }
    public void Enqueue(T item){
        ...;
    }
    public T Dequeue(){
        ...;
        T queueItem=this.data[this.tail];
        ...;
        return queueItem;
    }
}

一般是使用单字符T,也可以用其他的标识符代替。下面创建QUeue对象:

Queue<int>intQueue=new Queue<int>();
Queue<Horse>horseQueue=new Queue<int>();
intQueue.Enqueue(99);
int myInt=intQueue.Dequeue();
Horse myHorse=intQueue.Dequeue();//错误

17.2.1 对比泛型类和常规类

泛型类相当于定义了一种模板,编译器根据需要用该模板来生成新的、有具体类型的类。泛型类的具体类型版本称为已构造类型。

17.2.2 泛型和约束

有时我们需要确保泛型类使用的类型参数是提供了特定方法的类型。如:

public class PrintableCollection<T> where T:IPrintable

这个类编译时,编译器会验证替换T的类型有没有实现IPrintable接口,没有的话就会编译错误。

17.3 创建泛型类

(.Net Framework类库在System.Collections.Generic命名空间提供了大量现成的泛型类。)

17.3.1 二叉树理论

二叉树(binary tree是一种有用的数据结构,可用它来实现大量的操作。

二叉树是一种递归数据结构,要么为空,要么包含3个元素:一个数据,通常称为节点,两个子树–左子树右子树。子树要么为空,要么包含一个节点和另外两个子树。这样这个结构可以无限下去。

二叉树的强大体现在数据排序上。如在排好序的二叉树B中插入数据项I的算法如下:

If the tree,B,is empty
Then
	Construct a new tree B with the new item I as the node, and empty left and right sub-trees
Else 
	Examine the value of the current node,N,of the tree,B
	If the value of N is greater than that of the new item,I
	Then
		If the left sub-tree of B is empty
		Then
			Construct a new left sub-tree of B with the item I as the node, and empty left and right sub-trees
		Else
			Insert I into the left-tree of B
		End IF
	Else 
		if the right sub-tree of B is empty
		Then
			Construct a new right sub-tree of B with the item I as the node, and empty left and right sub-trees
		Else
			insert I into the right sub-tree of B
		End If
	End If
End IF

从最开始的一个空的二叉树和一个无序对象序列,我们可以利用上面的算法将每个对象插入二叉树,最终获得一个有序树。然后我们可以依次访问每个节点,通过下面的算法:

If the left sub-tree is not empty
THen
	Display the contents of the left sub-tree
End If
Display the value of the node
If the right sub-tree is not empty
Then
	Display the contents of the right sub-tree
ENd IF

17.3.2 使用泛型构造二叉树类

下面我们将用泛型来定义一个二叉树类,它能容纳几乎所有类型的数据,前提是该类型提供一种方式来比较来给你个实例的值。

首先是我们的二叉树类Tree.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace C_17_3_2
{
    public class Tree<TItem> where TItem:IComparable<TItem>
    {
        public TItem NodeData { get; set; }
        public Tree<TItem> LeftTree { get; set; }
        public Tree<TItem> RightTree { get; set; }
        public Tree(TItem nodeValue){
            this.NodeData=nodeValue;
            this.LeftTree = null;
            this.RightTree = null;
        }
        public void Insert(TItem newItem)
        {
            TItem currentNodeValuie = this.NodeData;
            if (currentNodeValuie.CompareTo(newItem) > 0)
                if (this.LeftTree == null)
                    this.LeftTree = new Tree<TItem>(newItem);
                else
                    this.LeftTree.Insert(newItem);
            else
                if (this.RightTree == null)
                    this.RightTree = new Tree<TItem>(newItem);
                else
                    this.RightTree.Insert(newItem);
        }
        public string walkTree()
        {
            string result = "";
            if (this.LeftTree != null)
                result = this.LeftTree.walkTree();
            result += $" {this.NodeData.ToString()} ";
            if (this.RightTree != null)
                result += this.RightTree.walkTree();
            return result;
        }
    }
}

然后是Program.cs

using System;

namespace C_17_3_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Tree<int> tree1 = new Tree<int>(10);
            tree1.Insert(5);
            tree1.Insert(11);
            tree1.Insert(5);
            tree1.Insert(-12);
            tree1.Insert(15);
            tree1.Insert(0);
            tree1.Insert(14);
            tree1.Insert(-8);
            tree1.Insert(10);
            tree1.Insert(8);
            tree1.Insert(8);
            string sortedData = tree1.walkTree();
            Console.WriteLine($"Sorted data is :{sortedData}");
            Tree<string> tree2 = new Tree<string>("Hello");
            tree2.Insert("World");
            tree2.Insert("How");
            tree2.Insert("Are");
            tree2.Insert("You");
            tree2.Insert("Today");
            tree2.Insert("I");
            tree2.Insert("Hope");
            tree2.Insert("You");
            tree2.Insert("Are");
            tree2.Insert("Feeling");
            tree2.Insert("Well");
            tree2.Insert("!");
            sortedData = tree2.walkTree();
            Console.WriteLine($"Sorted data is :{sortedData}");
        }
    }
}

运行结果为
在这里插入图片描述

17.4 创建泛型方法

泛型方法允许采取和泛型类相似的方式,用类型参数指定参数和返回类型。如:

static void Swap<T>(ref T first, ref T second){
    T temp=first;
    first=second;
    second=temp;
}

Swap<T>方法:

int a=1,b=2;
Swap<int>(ref a,ref,b);
...;
string s1="Hello",s2="world";
Swap<string>(ref s1,ref s2);

比如我们前面的程序,将Program.cs中代码修改以下,增加一个静态方法可以依次给二叉数插入更多数据:

using System;

namespace C_17_3_2
{
    class Program
    {
        static void InserIntoTree<TItem>(ref Tree<TItem> tree,params 
            TItem[] data)where TItem:IComparable<TItem>
        {
            foreach(TItem datum in data)
            {
                if (tree == null)
                    tree = new Tree<TItem>(datum);
                else
                    tree.Insert(datum);
            }
        }
        static void Main(string[] args)
        {
            Tree<char> charTree = null;
            InserIntoTree<char>(ref charTree, 'M', 'X', 'A', 'M', 'Z', 'Z', 'N');
            string sortedData = charTree.walkTree();
            Console.WriteLine($"Sorted data is : {sortedData}");
        }
    }
}

17.5 可变性和泛型接口

泛型接口和类:

interface IWrapper<T>{
    void SetData(T data);
    T GetData();
}
class Wrapper<T>:IWrapper<T>{
    private T storedData;
    void IWrapper<T>.SetData(T data){
        this.storedData=data;
    }
    T IWrapper<T>.GetData(){
        return this.storedData;
    }
}

Wrapper<T>提供一个简单的包装器。可以像下面这样创建该类的实例并用它类包装一个字符串:

Wrapper<string> stringWrapper=new Wrapper<string>();
IWrapper<string> storedStringWrapper=stringWrapper;
storedStringWrapper.SetData("Hello");
Console.WriteLine($"存储的值是{storedStringWrapper.GetData()}");

IWrapper<T>接口称为不变量。不能将IWrapper<A>对象赋值为IWrapper<B>类型的引用。

17.5.1 协变接口

假如定义下面的两个接口以及它们的实现类:

interface IStoreWrapper<T>{
void SetData(T data);
}
interface IRetriveWrapper<T>{
    T GetData();
} 
class Wrapper<T>:IStroeWrapper<T>,IRetriveWrapper<T>{
    private T storedData;
    void IStroeWrapper<T>.SetData(T data){
        this.storedData=data;
    }
    T IRetriveWrapper<T>.GetData(){
        return this.storedData;
    }
}

Wrapper<T>类的用法和前面一样,

Wrapper<string>stringWrapper=new Wrapper<string>();
IStroeWrapper<string>storedStringWrappper=stringWrapper;
storedStringWrapper.SetData("Hello");
IRetriveWrapper<string> retrievedStringWrappper=stringWrapper;
Console.WriteLine($"存储的值是{retrievedStringWrapper.GetData}");

但考虑如下代码:

IRetrieveWrapper<object> retrieveObjectWrapper=stringWapper;

简单的考虑,上面的代码应该是不合法的。但想想,IRetrieveWrapper<T>接口只允许读取IWrappper<T>对象中存储的数据,没有提供任何途径修改数据。这样的话可以明确告诉编译器一些隐式转换是合法的,不用强制严格的类型安全性。我们此时可以在声明类型参数时指定关键字out

interface IRetrieveWrapper<out T>{
    T GetData():
}

这个功能称为协变性。只要存在从类型A到B的有效转换,或者A派生自B,就可以将IRetrieveWrappper<A>对象赋给IRetrieveWrapper<B>引用。

这样下述代码就是可以运行的:

IRetrieveWrapper<object> retrieveObjectWrapper=stringWapper;

只有作为方法返回类型指定的类型参数才能使用out限定符。用类型参数指定方法的任何参数类型时,用out就是非法的。且协变性只适合引用类型。

17.5.2 逆变接口

你变性,允许泛型接口通过A类型的一个引用来引用D类型的一个对象,只要A从B派生。

比如,System.Collections.Generic命名空间提供了名为IComparer的接口:

public interface IComparer<in T>{
    int Compare(T x,T y);
}

下面代码根据对象的哈希码对它们进行排序:

class ObkectComparer:IComparer<Object>{
    itn Comparer<Object>.Compare(Object x,Object y){
        int xHash=x.GetHashCode();
        int yHash=y.GetHashCode();
        if(xHash==yHash)
            return 0;
        if(xHash<yHash)
            return 0;
        return 1;
    }
}

用法如下:

Object x=...;
Object y=...;
ObjectComparer objectComparer=new ObjectComparer();
IComparer<Object> objectComparator=objectComparer;
int result=objectComparator.Compare(x,y);

特别的:

IComparer<String> stringComparator=objectComparer;

上述语句时没问题的。注意IComparer接口的定义,类型参数前添加了in限定符。

in告诉编译器:程序要么传递T作为方法的参数列表,要么传递T的派生类型。程序员不能将T作为任何方法的返回类型。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值