如何确定一个.NET类型是自定义结构? [英] How to determine if a .NET Type is a custom struct?

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

问题描述

如何写一个简单的方法,来检查的具体类型是一个自定义的结构(与公共结构{}创建; )。与否

检查 Type.IsValueType 是远远不够的,因为它也是真实的 INT 等, 并增加了检查!IsPrimitiveType 将不排除十进制的DateTime ,也许一些其他的值类型。我知道,大多数的内置值类型实际上是结构,但我只想检查自定义结构

这些问题大多是相同的,但没有回答我需要:

  • #1
  • <一个href="http://stackoverflow.com/questions/2176298/how-to-determine-if-propertyinfo-type-is-a-struct">#2
  • #3

编辑:从提到的检查系统preFIX是最稳定的(尽管它仍然是一个黑客)的答案。我终于决定,以创建具有装饰与结构的属性,以便把它捡起来作为一个自定义的结构框架。 (其他的选择,我的想法是创建一个空的接口,让结构实现了空接口,但属性的方式似乎更优雅)

下面是我原来的自定义结构检查,如果有人有兴趣的话:

  type.IsValueType和放大器;&安培; !type.IsPrimitive和放大器;&安培; !type.Namespace.StartsWith(系统)及和放大器; !type.IsEnum
 

解决方案

嗯,日期时间,小数,等满足您的要求。至于CLR来讲,他们是自定义结构。一个黑客,但你可以检查是否命名空间以系统。

How to write a simple method, that checks whether a concrete type is a custom struct (created with public struct { };) or not.

Checking Type.IsValueType is not enough, because it is also true to int, long, etc, and adding a check to !IsPrimitiveType won't exclude decimal, DateTime and maybe some other value types. I know that most of the built in value types are actually "structs", but I only want to check for "custom structs"

These questions are mostly the same but without the answer I need:

EDIT: from the answers mentioned the "check for the 'System' prefix" was the most stable (although it's still a hack). I finally decided to create an Attribute that you have to decorate the struct with, in order the framework to pick it up as a custom struct. (The other choice I thought was to create an empty interface, and let the struct implement that empty interface, but the attribute way seemed more elegant)

Here is my original custom struct checker if someone if interested:

type.IsValueType && !type.IsPrimitive && !type.Namespace.StartsWith("System") && !type.IsEnum

解决方案

Well, DateTime, decimal, etc meet your requirements. As far as the CLR is concerned, they are custom structs. A hack, but you can just check to see if the namespace starts with "System".

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

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