如何确定类型是自定义结构? [英] How to decide a Type is a custom struct?

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

问题描述

对于 Type ,C#中具有属性 IsClass ,但是如何确定 Type 是结构?

For a Type, there is a property IsClass in C#, but how to decide a Type is a struct?

尽管 IsValueType 是必要条件,但显然还不够.对于 int 也是一种值类型.

Although IsValueType is a necessary condition, it is obviously not enough. For an int is a value type also.

有人建议以下代码:

bool IsStruct = type.IsValueType && !type.IsEnum && !type.IsPrimitive;

但是我不确定这是否是一种准确的方法.该公式应说明struct和其他类型(例如 DateTime int array s)之间的区别.

But I am not sure whether it is an accurate method. The formula should tell the difference between struct and other types such as DateTime, int and arrays.

正如一些朋友指出的那样,我的意思是用户定义的结构而不是预定义的类型,例如 DateTime .

As some friends have pointed out that here, I mean user defined struct and not predefined types, such as DateTime.

推荐答案

从技术上讲,int也是结构.IsPrimitive只是检查类型是否是CLR处理的基本类型之一.建议您 IsValueType&&!Enum&&!IsPrimitive .

Technically, an int is also a struct. IsPrimitive just checks if the type is one of the primitive types the CLR handles a little differently. You should be fine with the suggestion IsValueType && !IsEnum && !IsPrimitive.

如果仅需要自定义结构(即BCL不提供的结构),则可能会遇到排除以"System." 开头的FullName的类型,或者只包含您自己的结构的情况.对按程序集或名称空间进行过滤或使用自定义属性感兴趣.

If you want only custom structs (i.e. those not supplied by the BCL), you may have luck excluding types with a FullName that starts with "System.", or only including the ones you're interested in by filtering by assembly or namespace, or use a custom attribute.

这篇关于如何确定类型是自定义结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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