Why is typeof needed?

后端 未结 6 1393
独厮守ぢ
独厮守ぢ 2021-01-12 14:57

Something I\'ve been thinking about from time to time: Why is the typeof operator needed in C#? Doesn\'t the compiler know that public class Animal is a type ju

6条回答
  •  旧巷少年郎
    2021-01-12 15:25

    Animal is simply the name of the type, typeof(Animal) returns the actual type object (System.Type instance). Sure, it may have been possibly just to have the type name returning the type object in code, but it makes the job a lot harder for the compiler/parser (recognising when a type name means typeof or something else) - hence the existence of the typeof keyword. It also arguably makes the code clearer to read.

提交回复
热议问题