我正在尝试实现一个存储通用可空类型的类:
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)
我做错了什么或者我该如何解决这个问题?
这两个例子都没有编译:
<T?>是无效的语法; 它应该是<T>myclass需要where T : struct约束myclass<int> c = new myclass<int>();.然而,你的第二个例子的其余部分应该编译好.
| 归档时间: |
|
| 查看次数: |
627 次 |
| 最近记录: |