小编Pet*_*ter的帖子

Nullable类型作为通用参数

我正在尝试实现一个存储通用可空类型的类:

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

    public T? myfunction(){
        return myvariable;
    }
 }
Run Code Online (Sandbox Code Playgroud)

虽然上面的类编译得很好,但实际使用会带来麻烦:

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.
Run Code Online (Sandbox Code Playgroud)

我做错了什么或者我该如何解决这个问题?

c#

2
推荐指数
1
解决办法
627
查看次数

标签 统计

c# ×1