问题描述
如何以编程方式检查类型是结构还是类?
How to check programmatically if a type is a struct or a class?
推荐答案
使用:
像这样使用它:
typeof(Foo).IsValueType
或在执行时像这样:
fooInstance.GetType().IsValueType
还有一个属性(我认为该属性应称为 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;
这篇关于如何以编程方式检查类型是结构还是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!