在章泛型CLR通过C#V3,杰弗里里希特说下面TypeList<T>
有两个好处这里的编译时类型安全是什么意思?
- 编译时类型安全
- 拳击值类型
在List<Object>
,但如何编译时间型安全是否实现?
//A single instance of TypeList could hold different types.
using System;
using System.Collections.Generic;
using System.Text;
namespace MyNamespace
{
namespace Generics
{
class Node
{
private Node next_;
public Node(Node next) {
next_ = next;
}
public Node getNext() {
return next_;
}
}
internal sealed class TypeList<T> :Node
{
T data_;
public T getData() {
return data_;
}
public TypeList(T data, Node next):base(next) {
data_ = data;
}
public TypeList(T data):this(data,null) {
}
public override String ToString()
{
return data_.ToString() + (base.getNext() != null ? base.getNext().ToString() : string.Empty);
}
}
class Dummmy:Object
{
public override String ToString() {
return "Dummytype".ToString();
}
}
class Program
{
static void Main(string[] args)
{
Dummmy dummy = new Dummmy();
Node list = new TypeList<int>(12);
list = new TypeList<Double>(12.5121, list);
list = new TypeList<Dummmy>(dummy, list);
Double a = ((TypeList<Double>)list).getData();//Fails at runTime invalid cast exception
Console.WriteLine(list.ToString());
Console.Write("sds");
}
}
}
}
好处是,泛型*不*值框类型,不是他们做的。 – Douglas 2010-10-25 08:40:06
是的我明白这个部分,但是如何实现编译时间类型安全或作者认为编译时间类型安全 – yesraaj 2010-10-25 08:42:11