Property or indexer cannot be assigned to — it is read only [duplicate]

。_饼干妹妹 提交于 2019-12-08 04:07:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!