Nullable DateTime中的年份

use*_*055 14 .net c#

如何计算nullable日期中的年份?

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--;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

'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?)   
Run Code Online (Sandbox Code Playgroud)

Ern*_*rno 46

替换DateofDiagnosis.YearDateofDiagnosis.Value.Year

并检查DateofDiagnosis.HasValue以确保它不是一个空的第一个.

我会写这样的代码:

private bool TryCalculateAgeAtDiagnosis(
                 DateTime? dateOfDiagnosis, 
                 DateTime? dateOfBirth, 
                 out int ageInYears)
{
    if (!(dateOfDiagnosis.HasValue && dateOfBirth.HasValue))
    {
        ageInYears = default(int);
        return false;
    }

    ageInYears = dateOfDiagnosis.Value.Year - dateOfBirth.Value.Year;

    if (dateOfBirth > dateOfDiagnosis.Value.AddYears(-ageInYears))
    {
        ageInYears--;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)


ion*_*den 7

首先检查它是否有Value:

if (date.HasValue == true)
{
    //date.Value.Year;
}
Run Code Online (Sandbox Code Playgroud)