如果我们在C#中没有这个功能,我们如何在C#中实现可空类型?
You can wrap a native type into a struct (quick example to give you an idea, untested, lots of room for improvement):
public struct NullableDouble {
public bool hasValue = false;
private double _value;
public double Value {
get {
if (hasValue)
return _value;
else
throw new Exception(...);
}
set {
hasValue = true;
_value = value;
}
}
}
Clearly, you won't get the syntactic sugar of newer C# versions, ie you have to use
(See Andreas' comment.) myNullableDouble.hasValue
instead of
myNullableDouble == null
, etc.
Nullable is a generic type. Without generics it is not possible to implement a nullable like that and wouldn't really make sense.
You can't, without attaching business rules to existing values in the data type. eg. int.MinValue can be used as a placeholder, but what if you need this value? If you have a rule where all values are positive, it could work, but not as "nullable".
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.