简体   繁体   中英

Nullable type as a generic parameter

I'm trying to implement a class that stores a generic nullable type:

public class myclass<T?>
{
    T? myvariable;

    public T? myfunction(){
        return myvariable;
    }
 }

And while the above class compiles just fine, the actual use that provides trouble:

myclass<int?> c = new myclass<int>();
int? = c.myfunction();   // does not work: implicit cast from type T? in int? not possible.
// or, assuming the variable is not null
int = c.myfunction().Value; // implicit cast from type T in int not possible.

What am I doing wrong or how can I work around this?

Neither of the examples compile:

The rest of your second example should compile OK, however.

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