nullable 객체는 값을 가져야합니다
예외 설명에 역설이 있습니다. Nullable 객체에는 값 (?!)이 있어야합니다.
이게 문제 야:
나는이 DateTimeExtended
그 있으며, 클래스를
{
DateTime? MyDataTime;
int? otherdata;
}
그리고 생성자
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime.Value;
this.otherdata = myNewDT.otherdata;
}
이 코드를 실행
DateTimeExtended res = new DateTimeExtended(oldDTE);
발생 InvalidOperationException
메시지와 함께 :
널 입력 가능 오브젝트에는 값이 있어야합니다.
myNewDT.MyDateTime.Value
-유효하며 일반 DateTime
객체를 포함 합니다.
이 메시지의 의미는 무엇이며 내가 뭘 잘못하고 있습니까?
참고 oldDTE
하지 않습니다 null
. Value
에서를 제거 myNewDT.MyDateTime
했지만 생성 된 setter로 인해 동일한 예외가 발생합니다.
줄 this.MyDateTime = myNewDT.MyDateTime.Value;
을 그냥 변경해야합니다this.MyDateTime = myNewDT.MyDateTime;
당신이 받고있는 예외 .Value
는 Nullable 의 속성에 던져졌습니다 DateTime
. DateTime
( .Value
주에 대한 계약 이기 때문에) DateTime
반환 해야하기 때문에 반환 할 수 없기 때문에 예외를 throw 할 수 없습니다.
일반적으로 .Value
변수 에 값이 있어야 한다는 사전 지식이 없으면 (예 : .HasValue
검사를 통해 ) 맹목적으로 nullable 형식을 호출하는 것은 좋지 않습니다 .
편집하다
DateTimeExtended
예외를 발생시키지 않는 코드는 다음과 같습니다 .
class DateTimeExtended
{
public DateTime? MyDateTime;
public int? otherdata;
public DateTimeExtended() { }
public DateTimeExtended(DateTimeExtended other)
{
this.MyDateTime = other.MyDateTime;
this.otherdata = other.otherdata;
}
}
나는 이것을 다음과 같이 테스트했다.
DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);
.Value
on을 추가하면 other.MyDateTime
예외가 발생합니다. 제거하면 예외가 제거됩니다. 당신이 잘못된 곳을보고 있다고 생각합니다.
(예를 들어 LINQ 확장 방법을 사용하는 경우 Select
, Where
), 람다 함수는 당신의 C # 코드에 동일하게 작동하지 않을 수 있습니다 그 SQL로 변환 할 수 있습니다. 예를 들어, C #의 단락 회로 평가 ||
와는 &&
SQL의 열망로 변환 AND
하고 OR
. 람다에서 null을 확인할 때 문제가 발생할 수 있습니다.
예:
MyEnum? type = null;
Entities.Table.Where(a => type == null ||
a.type == (int)type).ToArray(); // Exception: Nullable object must have a value
떨어 뜨리십시오 .value
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime;
this.otherdata = myNewDT.otherdata;
}
이 경우 oldDTE는 null이므로 oldDTE.Value에 액세스하려고하면 값이 없으므로 InvalidOperationException이 발생합니다. 귀하의 예에서 간단하게 할 수 있습니다 :
this.MyDateTime = newDT.MyDateTime;
.Value
파트 없이 멤버를 직접 지정하십시오 .
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime;
this.otherdata = myNewDT.otherdata;
}
oldDTE.MyDateTime이 null 인 것처럼 보이므로 생성자가 값을 가져 오려고했습니다.
null 값을 가진 개체의 값에 액세스하려고 할 때이 메시지가 나타납니다.
sName = myObj.Name;
this will produce error. First you should check if object not null
if(myObj != null)
sName = myObj.Name;
This works.
참고URL : https://stackoverflow.com/questions/1896185/nullable-object-must-have-a-value
'Programming' 카테고리의 다른 글
Emacs 내에서 su / sudo가있는 파일 열기 (0) | 2020.05.25 |
---|---|
NoClassDefFoundError : android.support.v7.internal.view.menu.MenuBuilder (0) | 2020.05.25 |
Oracle tnsnames.ora에서 SID가 서비스 이름과 다른 점 (0) | 2020.05.25 |
렌즈, fclabels, 데이터 접근 자-구조 접근 및 돌연변이를위한 라이브러리가 더 좋습니다 (0) | 2020.05.25 |
알림 시스템 구축 [폐쇄] (0) | 2020.05.25 |