可空对象必须有一个价值 [英] nullable object must have a value
问题描述
有矛盾是在异常的描述:
可空对象必须有一个值(?!)
There is paradox in the exception description: Nullable object must have a value (?!)
这就是问题所在:
我有一个 DateTimeExtended
类,
有
I have a DateTimeExtended
class,
that has
{
DateTime? MyDataTime;
int? otherdata;
}
和构造
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime.Value;
this.otherdata = myNewDT.otherdata;
}
运行此code
running this code
DateTimeExtended res = new DateTimeExtended(oldDTE);
引发出现InvalidOperationException
与消息:
可空对象必须有一个值。
Nullable object must have a value.
myNewDT.MyDateTime.Value
- 是有效的,并包含正规的DateTime
对象
myNewDT.MyDateTime.Value
- is valid and contain a regular DateTime
object.
这是什么消息的含义,什么我做错了?
What is the meaning of this message and what am I doing wrong?
注意 oldDTE
不是空
。我已删除了值
从 myNewDT.MyDateTime
但同样的异常抛出因于所产生的制定者。
Note that oldDTE
is not null
. I've removed the Value
from myNewDT.MyDateTime
but the same exception is thrown due to a generated setter.
推荐答案
您应该更改行 this.MyDateTime = myNewDT.MyDateTime.Value;
只是 this.MyDateTime = myNewDT.MyDateTime;
您正在接受可空的DateTime的.Value属性被抛出,因为它是需要返回一个DateTime(因为那是在合同.value的状态),但它不能这样做,因为没有例外日期时间返回,所以它抛出一个异常。
The exception you were receiving was thrown in the .Value property of the Nullable DateTime, as it is required to return a DateTime (since that's what the contract for .Value states), but it can't do so because there's no DateTime to return, so it throws an exception.
在一般情况下,这是一个坏主意,一味呼吁。价值上可空类型,除非你有一些事先知道该变量必须包含一个值(即通过的HasValue检查)。
In general, it is a bad idea to blindly call .Value on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a HasValue check).
修改
这里的code为DateTimeExtended不抛出异常:
Here's the code for DateTimeExtended that does not throw an exception:
class DateTimeExtended
{
public DateTime? MyDateTime;
public int? otherdata;
public DateTimeExtended() { }
public DateTimeExtended(DateTimeExtended other)
{
this.MyDateTime = other.MyDateTime;
this.otherdata = other.otherdata;
}
}
我测试了它是这样的:
I tested it like this:
DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);
在other.MyDateTime添加.value的导致异常。删除它摆脱了异常。我想你找错了地方。
Adding the .Value on other.MyDateTime causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.
这篇关于可空对象必须有一个价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!