为什么需要typeof? [英] Why is typeof needed?

查看:56
本文介绍了为什么需要typeof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不时在思考的事情:为什么在C#中需要typeof运算符?编译器难道不仅仅根据定义就知道 public class Animal 是一种类型吗?当我需要引用类型时,为什么需要指定 SomeMethod(typeof(Animal))?

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 just by the very definition? Why do I need to specify SomeMethod(typeof(Animal)) when I need to reference a type?

推荐答案

typeof(Class)是将Type表示为文字的唯一方法.编写 Class.SomeField 时,是指静态字段.编写 typeof(Class).SomeField 时,您引用表示您的类的 Type 类的对象的字段.

typeof(Class) is the only way to express Type as a literal. When you write Class.SomeField you mean static field. When you write typeof(Class).SomeField you reference field of object of class Type that represents your class.

这篇关于为什么需要typeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆