Compile-time typesafety的含义是什么?

yes*_*aaj 2 c# generics .net-2.0

在Generics CLR Via C#v3一章中,Jeffrey Richter说下面TypeList<T>有两个优点

  1. 编译时类型安全
  2. 拳击价值类型

结束了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");
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

And*_*zub 5

编译类型安全意味着您将在编译时获得有关无效类型使用的所有错误,但不会在运行时获得.

例如,以下代码会导致编译时错误:

TypeList<int> list = new TypeList<int>(1);
string someString = list.getData(); // compile error here
Run Code Online (Sandbox Code Playgroud)

如果你使用TypeList<object>那里将没有编译时安全性,因为编译器不会报告错误,你会得到运行时错误:

TypeList<object> list = new TypeList<object>(1);
string someString = (string)list.getData(); // runtime error here
Run Code Online (Sandbox Code Playgroud)