栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

类型检查:typeof,GetType还是?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类型检查:typeof,GetType还是?

都是不同的。

  • typeof
    采用类型名称(您在编译时指定)。
  • GetType
    获取实例的运行时类型。
  • is
    如果实例在继承树中,则返回true。

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"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/594637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号