簡體   English   中英

在自動屬性中替代私人設置器

[英]Alternative to private setters in Automatic properties

如果您不應該將私有設置器用於自動屬性(不好的做法),那么我如何在班級內部對其進行私有設置,並且仍然可以向公眾公開呢? (可以說我想在構造函數級別設置它,但仍然允許它通過get公開)?

示例類:

public class Car
{
    //set the property via constructor
    public SomeClass(LicensePlate license)
    {
         License = license
    }

    public LicensePlate License{get; private set;} // bad practice
}

您將屬性轉換為一個沒有后備字段的后備字段。

public class Car
{
    LicensePlate _license;

    public Car(LicensePlate license)
    {
        _license = license;
    }

    public LicensePlate License
    {
        get { return _license; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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