How to identify if a Type is a custom struct?

2019-06-17 02:08发布

For a Type, there is a property IsClass, but how to know a Type is a struct?

Sorry, I have to add some more information.

  1. I am using C#.
  2. Although IsValueType is a necessary condition, it is obviously not enough. For an Integer is a value type also.

6条回答
Bombasti
2楼-- · 2019-06-17 02:38

use this:

 x.GetType().IsValueType();

From help:

Type::IsValueType Property Gets a value indicating whether the Type is a value type. Value types are types that are represented as sequences of bits; value types are not classes or interfaces. Value types are referred to as "structs" in some programming languages. Enums are a special case of value types.

查看更多
forever°为你锁心
3楼-- · 2019-06-17 02:44
t.IsValueType && !t.IsPrimitive && !t.IsEnum;
查看更多
三岁会撩人
4楼-- · 2019-06-17 02:49

If it's a value type (e.g., a struct), use Type.IsValueType.

查看更多
Viruses.
5楼-- · 2019-06-17 02:52

Well then, I guess for your requirement then this comes close:

bool isStruct = myType.IsValueType && !myType.IsPrimitive;

but still DateTime isn't covered by that for example. Maybe you would have to add further types you want to exlude manually.

查看更多
小情绪 Triste *
6楼-- · 2019-06-17 02:54

You can use IsValueType.

查看更多
欢心
7楼-- · 2019-06-17 02:58

If you are talking about c#, you can use the IsValueType property.

查看更多
登录 后发表回答