如何检查编程如果一个类型是一个结构或类? [英] How to check programatically if a type is a struct or a class?

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

问题描述

我觉得这个问题是清楚的。

I think the question is clear.

推荐答案

使用<一个href="http://msdn.microsoft.com/en-us/library/system.type.isvaluetype.aspx"><$c$c>Type.IsValueType:

获取一个指示的类型是否是值类型。

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

使用它或者是这样的:

typeof(Foo).IsValueType

或类似这样的执行时间:

or at execution time like this:

fooInstance.GetType().IsValueType



相反也有<一个href="http://msdn.microsoft.com/en-us/library/system.type.isclass.aspx"><$c$c>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似乎总是看而不布尔否定更好,所以无论使用何种帮助您code的可读性。

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


由于斯特凡指出的下方,以正确识别的结构的你一定要小心,以避免误判,当涉及到枚举。一个枚举是一个值类型,这样 IsValueType 属性将返回枚举以及结构

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天全站免登陆