发新话题
打印

[语法] 泛型中default关键字的用法

泛型中default关键字的用法

泛型所以会用到default关键字,是因为需要在不知道类型参数为值类型还是引用类型的情况下,为对象实例赋初值。考虑以下代码: class TestDefault { public T foo() { T t = null; //??? return t; } } 如果我们用int型来绑定泛型参数,那么T就是int型,那么注释的那一行就变成了 int t = null;显然这是无意义的。为了解决这一问题,引入了default关键字: class TestDefault { public T foo() { return default(T); } } 以下是测试用的代码,看了之后就应该很快能明白,default关键字的作用: class Program { static void Main(string[] args) { TestDefault t1 = new TestDefault(); int i = t1.foo(); System.Diagnostics.Debug.Assert(i == 0); //断言 TestDefault t2 = new TestDefault(); object o = t2.foo(); System.Diagnostics.Debug.Assert(o == null); } } 最后说明一下,在.net 2.0的早期preview中,没有default关键字,使用如下的方式实现default关键字的功能: class TestDefault { public T foo() { return T.default; } } 这段代码在vs 2005 beta1中,已经不能通过编译了。

TOP

发新话题