[英]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.