都是不同的。
例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始终是表达式的类型。请记住,泛型方法基本上是一堆具有适当类型的方法。例:
string Foo<T>(T parameter) { return typeof(T).Name; }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 aboveFoo<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"
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)