Csharp/CSharp Tutorial/Generic/Type constaint

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

A reference constriant

using System; 
 
class MyClass { 
} 
 
class Test<T> where T : class { 
  T obj; 
 
  public Test() { 
    // Here T must be a reference type, 
    // which can be assigned the value null. 
    obj = null; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    // The following is OK because MyClass is a class. 
    Test<MyClass> x = new Test<MyClass>(); 
 
    // The next line is in error because int is a value type. 
    // Test<int> y = new Test<int>(); 
  } 
}

A value type constriant

using System; 
 
struct MyStruct { 
} 
 
class MyClass { 
} 
 
class Test<T> where T : struct { 
  T obj; 
 
  public Test(T x) { 
    obj = x; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Test<MyStruct> x = new Test<MyStruct>(new MyStruct()); 
    Test<int> y = new Test<int>(10); 
 
    // illegal! 
    // Test<MyClass> z = new Test<MyClass>(new MyClass()); 
  } 
}

Static Field Per Closed Type

using System;
using System.ruponentModel;
using System.Text;
        class TypeWithField<T>
        {
            public static string field;
            public static void PrintField()
            {
                Console.WriteLine(field + ": " + typeof(T).Name);
            }
            static void Main()
            {
                TypeWithField<int>.field = "First";
                TypeWithField<int>.PrintField();
            }
        }