2012-03-30 33 views
11

Làm cách nào để tính năm trong ngày nullable?Năm trong Thời gian rảnh rỗi

partial void AgeAtDiagnosis_Compute(ref int result) 
{ 
    // Set result to the desired field value 
    result = DateofDiagnosis.Year - DateofBirth.Year; 
    if (DateofBirth > DateofDiagnosis.AddYears(-result)) 
    { 
     result--; 
    } 
} 

Lỗi này là:

'System.Nullable<System.DateTime>' does not contain a definition for 'Year' and no 
extension method 'Year' accepting a first argument of 
type 'System.Nullable<System.DateTime>' could be found (are you missing a using 
directive or an assembly reference?) 
+0

Liệu nó làm việc với DateTime thật không? Nếu vậy bạn không thể sử dụng giá trị không null. Có vẻ như nếu nó không phải là tính toán năm là không cần thiết anyway? – TGH

+0

Bạn nên tìm kiếm trên google https://www.google.co.in/search?q=nullable+datetime+in+c%23 – Prakash

Trả lời

34

Thay DateofDiagnosis.Year với DateofDiagnosis.Value.Year

Và kiểm tra DateofDiagnosis.HasValue để chắc chắn nó không phải là một null đầu tiên.

0

Sử dụng nullableDateTime.Value.Year.

6

Đầu tiên kiểm tra nếu nó có một Value:

if (date.HasValue == true) 
{ 
    //date.Value.Year; 
} 
0

Mã của bạn có thể trông như thế này,

partial void AgeAtDiagnosis_Compute(ref int result) 
     { 
      if(DateofDiagnosis.HasValue && DateofBirth.HasValue) 
      { 
       // Set result to the desired field value 
       result = DateofDiagnosis.Value.Year - DateofBirth.Value.Year; 
       if (DateofBirth > DateofDiagnosis.Value.AddYears(-result)) 
       { 
        result--; 
       } 
      } 
     } 
Các vấn đề liên quan