简体   繁体   中英

How to set calculate variable to property in class

I have a following class and i want to set YearCreated = 2023-age how i can do it?

public class Car
{
    public string Id { get; set; }
    public Producent Producent { get; set; }
    public int Age { get; set; }
    public int YearCreated { get; set; } 
    public Engine Engine { get; set; }

}

Here you can find details Using Properties

It will be something like

 public class Car
    {
        public int Age { get; set; }
        public int YearCreated => DateTime.Now.Year - Age;
    }

You could turn YearCreated into an expression-bodied property . See below for example.

Note that this makes the property read-only. If you need to be able to override the property, you will need to add a backing field and give the property a body.

public class Car
{
    public string Id { get; set; }
    public Producent Producent { get; set; }
    public int Age { get; set; }
    public int YearCreated => 2023 - Age;
    public Engine Engine { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM