typeof
#微头条创作计划# 去五台山拜佛,大师送我一段话,说的全是英语,楞是不知道说什么,现在连和尚都是高学历吗?大师原话:the most type of thing in life is completely ness. some people have bad marriage, but the children are fine. some people have bad marriages, but the health may not be so good. the best state of life is to find a shortage. be not satisfied. you can't share all your blessings with others. writin's does not occupy all, but leave three others. the impermanence of life must learn to be content. contented people are poor, and rich love is better than contentment.
最后大师让我自己去悟,悟透就会快乐!求解……
typeof什么意思
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)呢?返回的也是编译时类型吗?是的。泛型方法基本上只是一系列具有适当类型的方法。看下面的例子:
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); // 调用 Foo<Animal> 返回 "Animal"Foo<Animal>(probably_a_dog); //与上面的一样Foo<Dog>(probably_a_dog); // !!! 编译错误. 期望参数Dog, 你输入Animal.Foo(definitely_a_dog); // 调用 Foo<Dog> 返回 "Dog"Foo<Dog>(definitely_a_dog); // 与上面的一样Foo<Animal>(definitely_a_dog); // 调用 Foo<Animal> 返回 "Animal". Foo((Animal)definitely_a_dog); // 与上面的一样
typeof原理
A type of后面通常跟名词指代某一类型某一种类。它是一个短语,通常情况下他表示某一类型的事物或种类。他后面跟名词既可以跟名词的单数形式,也可以跟复数形式,要看具体表达的是什么东西,什么种类,要根据具体情况变化来定,不是固定的。