在通过 C# v3 的泛型 CLR 一章中,Jeffrey Richter 在下面说 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");
}
}
}
}
最佳答案
编译类型安全意味着您会在编译时收到所有关于无效类型使用的错误,但不会在运行时。
例如下面的代码会导致编译时错误:
TypeList<int> list = new TypeList<int>(1);
string someString = list.getData(); // compile error here
如果你使用了 TypeList<object>
不会有编译时安全,因为编译器不会报告错误,你会得到运行时错误:
TypeList<object> list = new TypeList<object>(1);
string someString = (string)list.getData(); // runtime error here
关于c# - 这里的编译时类型安全是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4012937/