Csharp/CSharp Tutorial/Generic/default

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Default generic value

using System;
public class Bag<T>
{
    public Bag() {
        imp = new T[ 4 ];
        for( int i = 0; i < imp.Length; ++i ) {
            imp[i] = default(T);
        }
    }
    public bool IsNull( int i ) {
        if( imp[i] == null ) {
            return true;
        } else {
            return false;
        }
    }
    private T[] imp;
}
public class EntryPoint
{
    static void Main() {
        Bag<int> intBag = new Bag<int>();
        Bag<object> objBag = new Bag<object>();
        Console.WriteLine( intBag.IsNull(0) );
        Console.WriteLine( objBag.IsNull(0) );
    }
}
False
True

Demonstrate the default keyword.

using System; 
 
class MyClass { 
} 
 
// Construct a default object of T. 
class Test<T> {  
  public T obj; 
 
  public Test() { 
    // obj must be a reference type. 
    // obj = null; 
 
    // This statement works for both  
    // reference and value types. 
    obj = default(T); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Test<MyClass> x = new Test<MyClass>(); 
 
    if(x.obj == null) 
      Console.WriteLine("x.obj is null."); 
 
    Test<int> y = new Test<int>(); 
 
    if(y.obj == 0) 
      Console.WriteLine("y.obj is 0."); 
  } 
}
x.obj is null.
y.obj is 0.