简体   繁体   中英

The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

I create a generic class:

public class Pair<L, R>
{
    public L? left;
    public R? right;
    // some code
}

I want to use there null-able variables for generic types. Compiler gives the error:

The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

What should be the correct construct in this case to overcome this error? Thank you.

You can constrain them to be value types:

 public class Pair<L, R>  
     where L: struct
     where R: struct

But that disallows reference types (classes), it's not clear if that is what you want.
When L and R are reference types you don't need the ?

Writing a generic Pair that allows both is a lot harder. I'm not sure if it can be done directly. Maybe in C# 8.

Otherwise you'll need some wrapper around the members.

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