[英]How to set calculate variable to property in class
我有以下 class,我想設置 YearCreated = 2023-age 我該怎么做?
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; }
}
在這里您可以找到使用屬性的詳細信息
會是這樣的
public class Car
{
public int Age { get; set; }
public int YearCreated => DateTime.Now.Year - Age;
}
您可以將 YearCreated 變成一個expression-bodied property 。 例如,請參見下文。
請注意,這會使該屬性變為只讀。 如果您需要能夠覆蓋該屬性,則需要添加一個支持字段並為該屬性提供一個主體。
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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.