Property or indexer cannot be assigned to

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--;
        }
}

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;

TimeSpane age0 = this.DateOfDiagnosis - this.DateOfBirth;

int age1 = (int) Math.Trunc( age0.TotalDays / 365.25);

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

链接地址: http://www.djcxy.com/p/54360.html

上一篇: 在SQL和C#中基于出生日期计算年龄?

下一篇: 属性或索引器不能分配给