如何以编程方式检查类型是结构还是类? [英] How to check programmatically if a type is a struct or a class?

查看:94
本文介绍了如何以编程方式检查类型是结构还是类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式检查类型是结构还是类?

How to check programmatically if a type is a struct or a class?

推荐答案

使用 Type.IsValueType


获取一个值,该值指示Type是否为值类型。

Gets a value indicating whether the Type is a value type.

像这样使用它:

typeof(Foo).IsValueType

或在执行时像这样:

fooInstance.GetType().IsValueType






还有一个 Type.IsClass 属性(我认为该属性应称为 IsReferenceType ,但这无关紧要),该属性可能更适合或更不适合您基于您要测试的内容。


Conversely there is also a Type.IsClass property (which should have been called IsReferenceType in my opinion but no matter) which may or may not be more appropriate for your uses based on what you are testing for.

在没有布尔取反的情况下,代码似乎总是读起来更好,因此请使用有助于提高代码可读性的东西。

Code always seems to read better without boolean negations, so use whichever helps the readability of your code.

正如Stefan在下面指出的那样,为了正确识别 struct ,您必须小心避免在枚举方面出现误报枚举是一种值类型,因此 IsValueType 属性将返回 true 用于枚举以及结构

As Stefan points out below, in order to properly identify structs you must be careful to avoid false positives when it comes to enums. An enum is a value type so the IsValueType property will return true for enums as well as structs.

因此,如果您真正在寻找结构,而不仅仅是一般的值类型,则需要这样做:

So if you truly are looking for structs and not just value types in general you will need to do this:

Type fooType = fooInstance.GetType();
Boolean isStruct = fooType.IsValueType && !fooType.IsEnum;

这篇关于如何以编程方式检查类型是结构还是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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