1. 程式人生 > >[C#]typeof,Gettype()和is的區別

[C#]typeof,Gettype()和is的區別

  1. typeof 引數是一個型別名稱,比如你自己編寫的一個類
  2. GetType()是類的方法,繼承自object,返回該例項的型別
  3. is 用來檢測例項的相容性(是否可以相互轉換)

例:

class Animal { } 
class Dog : Animal { }

void PrintTypes(Animal a) { 
    Console.WriteLine(a.GetType() == typeof(Animal)); // false 
    Console.WriteLine(a is Animal);                   // true 
    Console.WriteLine(a.GetType() == typeof
(Dog)); // true Console.WriteLine(a is Dog); // true } Dog spot = new Dog(); PrintTypes(spot);

 

對於泛型:typeof(T)

T總是表示式的型別,泛型方法基本上是一組具有適當型別的方法

例:

            Animal probably_a_dog = new Dog();
            Dog definitely_a_dog = new Dog();

            Foo(probably_a_dog); 
// this calls Foo<Animal> and returns "Animal" Foo<Animal>(probably_a_dog); // this is exactly the same as above Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal. Foo(definitely_a_dog);
// this calls Foo<Dog> and returns "Dog" Foo<Dog>(definitely_a_dog); // this is exactly the same as above. Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal". Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"