簡體   English   中英

如何在 class 中將計算變量設置為屬性

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM