Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c# - How to decide a Type is a custom struct?

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

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

Someone suggests the following code:

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...