自定义一个非空类型NonNullable<T>,要求T必须为引用类型,并通过该类来限制T不能取空值null。
在程序中测试该自定义类型的用法。

解决方案 »

  1.   

    T : class 引用,不能为null,这个好像不行吧,既然是引用,就可以为空
      

  2.   


        class NonNullable<T>
            where T : class
        {
            List<T> tlist = new List<T>();
            public void Add(T t)
            {
                if (t == null)
                {
                    throw new ArgumentNullException("t");
                }
                tlist.Add(t);
            }
        }        static void Main(string[] args)
            {
                NonNullable<string> nn = new NonNullable<string>();
                nn.Add(null);
            }
    没有这样的泛型约束,只可以运行时检查。