class BaseNode{}
class BaseNodeGeneric<T>{}
//concrete type
class NodeConcrete<T> : BaseNode{}
//closed constructed type
class NodeClosed<T> : BaseNodeGeneric<int>{}
//opend constructed type
class NodeOpen<T> : BaseNodeGeneric<T>{}
多态是动态的,泛型是静态的。
默认的是这个。
T tmp = default(T);
c# generic 没有c++ template 那么灵活,但是安全。
作业:自己实现一个容器类型,需要有构造、add、remove、clear、[]等方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication4
{
public class GenericList<T>
{
private T[] array;
private int length;
private int size;
public GenericList(int length){
this.length = length; //length是分配的长度(这里后面几乎没有再使用过length,也没有在增加的时候更改过length,其实是不对的)
this.size = 0; //size是实际有内容的长度
this.array = new T[length];
}
public T add(T data)
{
this.array[size++] = data;
return data;
}
public bool remove(T data)
{
for(int i = 0;i < size; i++)
{
if (data.Equals(this.array[i]))
{
for(int j = i;j< this.size; j++)
{
array[j] = array[j + 1];
}
size--;
return true;
}
}
return false;
}
public bool clear()
{
if (size > 0)
{
for (int i = 0; i < this.size; i++)
{
array[i] = default(T); //使用默认的值
}
size = 0;
return true;
}
else
return false;
}
public T this[int location]
{
get
{
return array[location];
}
}
}
class Program
{
static void Main(string[] args)
{
GenericList <String> randme= new GenericList<String>(10);
randme.add("littlepig");
randme.add("smallduck");
// Console.WriteLine(randme.size);
/// Console.WriteLine(randme.remove("smallduck"));
randme.clear();
// Console.WriteLine(randme.size);
Console.WriteLine(randme[1]);
Console.ReadLine();
}
}
}