How do I check if a type T
fits the unmanaged
type constraint, such that it could be used in a context like this: class Foo<T> where T : unmanaged
? My first idea was typeof(T).IsUnmanaged
or something similar, but that isn't a property/field of the Type
class
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I am not sure if something like this already exists, but you could implement your own extension method similar to:
(update) For completeness, since recursion will be slow for structs with many nested members, the function can be made faster by caching the results:
According to
unmanaged
constraint documentations:An
unmanaged
type is a type that is not a reference type and doesn't contain reference type fields at any level of nesting.Also it's mentioned in C# language design documentations about unmanaged type constraint:
In order to satisfy this constraint a type must be a struct and all the fields of the type must fall into one of the following categories:
sbyte
,byte
,short
,ushort
,int
,uint
,long
,ulong
,char
,float
,double
,decimal
,bool
,IntPtr
orUIntPtr
.enum
type.unmanaged
constraint.Considerations
Usually calling
MakeGenericType
is the most reliable solution for validating generic type constraints which are enforced by CRL. Usually trying to implement validation by yourself is not a good idea because there may be a lot of rules which you should consider and there is always a chance for missing some of them. But be informed, at least at time of writing this answer, it's not working well forunmanaged
constraint..NET Core have a
RuntimeHelpers.IsReferenceOrContainsReferences
but at the time of writing this answer, .NET Framework doesn't have such function. I should mention that even usingIsReferenceOrContainsReferences
is not completely reliable for this task.For example see the issue which I posted here about two structure which doesn't have any reference type but one of them evaluated as managed, one of them unmanaged (maybe a compiler bug).
Anyway, for now depending to your preference and requirements, use one of the following solutions to detect which type can satisfy
unmanaged
generic type constraint.Option 1 - Using MakeGenericType
As an option, to check if the type can satisfy the
unmanaged
constraint, you can use the followingIsUnmanaged
extension method'.Option 2 - Writing your own method checking the documented rules
As another option, you can write your method checking documented rules for
unmanaged
constraint. The following code has more rules rather than other answer to be able to handle cases likeint?
or(int,int)
:More Information
You may find the following links useful: