[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"
上一篇:List使用Foreach 修改集合时,会报错的解决方案 (Error: Collection was modified; enumeration operation may not execute. ) - 摘自网络


下一篇:C# foreach获取集合元素索引的坑