简体   繁体   中英

Combining struct and new() generic type constraints

Having recently had reason to peruse the Nullable documentation, I noticed that the definition of Nullable looks like:

public struct Nullable<T> where T : struct, new()

I was of the (mis?)understanding that structs always have a public parameterless constructor, if this is correct, what does the new() type constraint add here?

For struct new doesn't make sense. For classes it does.

In your case it is a redundant.

public T FactoryCreateInstance<T>() where T : new()
{
return new T();
}

It make sense to specify new constraint in a case like above but not when it is already constrained to be struct.

Parameter less constructor for value types is a C# restriction and not a CLI restriction. Maybe this is why is it specified redundantly to leave some wiggle room for future.

Just noting this is valid, verifiable IL (ie

 .class public sequential ansi sealed StructNewStruct`1<valuetype .ctor ([mscorlib]System.ValueType) T>
     extends [mscorlib]System.ValueType

compiles, as does the simpler

 .class public sequential ansi sealed StructNewStruct`1<valuetype .ctor T>
     extends [mscorlib]System.ValueType

) but I don't yet have code that does anything different for these that a simple where T:struct (or (Of T As Structure) in VB.NET and <valuetype T> in IL) provides.

Specifically, Nullable structs are already not allowed for any generic argument with a simple struct constraint. (It does seem Nullable objects are classes for almost all purposes except storage.)

So, in summary, Nullable<T> 's current (equivalent of) where T:ValueType, struct, new() seems to currently be identical to where T:struct .

For your information I used my updated DotLisp that allows the creation of generic types (just using MakeGenericType ) to attempt to create a type of StructNewStruct<t> and StructStruct<t> (*) for all types in all assemblies of the 4.0 Framework that load without me trying to load "unusual" assemblies (eg System.Web may not have been loaded). (If there are any "special" types in "obscure" framework assemblies let me know and I'll ensure they're loaded and tried.) All types succeeded or failed the same with both structures.

(*) StructStruct<T> where T:struct

It doesn't have to have a parameterless constructor, and even if it does have one it doesn't have to be a public one. I believe that "new()" requires it to have both these things.

Edit: Yup, as per the MSDN documentation: "The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM