[英]C# generics: default non-null value for member
In this generic "class": 在这个通用的“类”中:
public class Param<ValueType>{
public ValueType value;
}
When ValueType
is string
I want value
to be non-null for all newly created instances of class without explicitly passing default value through constructor. 当
ValueType
为string
我希望所有新创建的类实例的value
都为非空,而无需通过构造函数显式传递默认值。 In my scenario ValueType
can only be int
, float
, bool
, string
or struct
(that doesn't need to be enforced). 在我的场景中,
ValueType
只能是int
, float
, bool
, string
或struct
(不需要强制执行)。
How can I do that? 我怎样才能做到这一点?
When I try to do this: 当我尝试这样做时:
public class Param<ValueType> where ValueType: new(){
public ValueType value = new ValueType();
}
class stops accepting strings. 类停止接受字符串。
When I remove new() constraint, I can no longer use new ValueType()
(obviously) and value
is null for all new instances of Param<string>
. 当我移除new()约束时,我不能再使用
new ValueType()
(显然),并且对于Param<string>
所有新实例, value
为null。
What can I do about it? 我该怎么办?
The reason why I want this to happen is because I have .Equals()
defined which does value.Equals(other.value)
, which causes exception to be thrown when value
is null. 我之所以想发生这种情况,是因为我定义了
.Equals()
来执行value.Equals(other.value)
,当value
为null时,这会引发异常。
You could: 你可以:
public class Param<ValueType>
{
public ValueType value = typeof(ValueType) == typeof(string) ? (ValueType)(object)string.Empty : default(ValueType);
}
note that default(int) == 0
and so on. 请注意,
default(int) == 0
等等。
Ah and for the comparison, you should: 嗯,为了进行比较,您应该:
bool areEqual = EqualityComparer<ValueType>.Equals(value, other.Value);
It correctly works for null
values. 它适用于
null
值。
Note even that with generics, this: 即使使用泛型,也要注意:
if (value == null)
{
}
is perfectly valid code. 是完全有效的代码。 Clearly it will be true only if
ValueType
can be null
and is null
(so for ValueType == int
it won't ever happen) 显然,只有当
ValueType
可以为null
且为null
它才会为真(因此对于ValueType == int
它将永远不会发生)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.