The is a 'struct' restriction in generic classes or methods in C#. I want to k开发者_开发知识库now It means structs only or any type derived from value type like int, double, enum, ant so on. Is the next code let me to use simple types?
class SomeGenericClass <T> where T : struct
{
//some inplementation
}
What does 'struct' restriction mean?
It means any non-nullable value type. All structs are value types.
I want to know It means structs only or any type derived from value type like int, double, enum, ant so on. Is the next code let me to use simple types?
Your so-called "simple types", like int
, double
and enum
are nothing more than C# keywords that correspond to the System.Int32
and System.Double
structs, and System.Enum
class which is based on System.ValueType
(which makes enums also value types, despite Enum
being a class itself).
Therefore these types also satisfy the where T : struct
constraint, along with regular structs.
It means T
can be only value type. value type is only those data structure which are defined with struct
keyword and enum
keyword.
For example,
struct A{}; //value-type
struct B{}; //value-type
class C{}; //reference-type
enum D {}; //value-type
SomeGenericClass<A> a; //ok
SomeGenericClass<B> b; //ok
SomeGenericClass<C> c; //compilation error - C is not value type
SomeGenericClass<D> d; //ok
As for int
, double
, float
and other built-in types, they're all value-types. Each of these keyword corresponds to a struct defined in the framework. For example, int
is basically System.Int32
, and double
is System.Double
, and so on.
taken from the C# language specification chapter 4.1.10:
A non-nullable value type conversely is any value type other than System.Nullable and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint).
so yes, this basically means T is restricted to value types, not reference types.
精彩评论