问题
I'm capturing date of Birth and Date of Diagnosis in database and would like to calculate age in years by Diagnosis date.
This is my code. But I have error following error.
Error 2 Property or indexer 'LightSwitchApplication.Patient.AgeAtDiagnosis' cannot be assigned to -- it is read only
partial void AgeAtDiagnosis_Compute(ref int result)
{
// Set result to the desired field value
AgeAtDiagnosis = DateofDiagnosis.Year - DateofBirth.Year;
if (DateofBirth > DateofDiagnosis.AddYears(-AgeAtDiagnosis))
{
AgeAtDiagnosis--;
}
}
回答1:
DateTime birth = new DateTime(1950, 01, 01);
DateTime diagnosis = new DateTime(2012, 02, 01);
TimeSpan Span = diagnosis - birth;
DateTime Age = DateTime.MinValue + Span;
// note: MinValue is 1/1/1 so we have to subtract...
int Years = Age.Year - 1;
回答2:
TimeSpane age0 = this.DateOfDiagnosis - this.DateOfBirth;
int age1 = (int) Math.Trunc( age0.TotalDays / 365.25);
回答3:
You can just subtract one date from another to give a TimeSpan. That has a TotalDays property from which you can derive years. It depends how accurate you want to be:
var ageInDays = (diagnoticDate - dateOfBirth).TotalDays;
var age = Convert.ToInt32(ageInDays / 365);
Obviously leap years cause issues so the other alternative is to inspect the year, month and day properties of each date and calculate their differences individually taking into account partial years etc
来源:https://stackoverflow.com/questions/9309770/property-or-indexer-cannot-be-assigned-to-it-is-read-only