[英]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'
该类型必须是非空值类型,才能在通用类型或方法“ System.Nullable”中用作参数“ T”
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 ?
当L和R是引用类型时,您不需要
?
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.
也许在C#8中。
Otherwise you'll need some wrapper around the members. 否则,您将需要一些围绕成员的包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.