簡體   English   中英

C#中的自定義自動屬性

[英]Custom auto properties in C#

我有以下類與自動屬性:

class Coordinates
{
    public Coordinates(int x, int y)
    {
        X = x * 10;
        Y = y * 10;
    }

    public int X { get; set; }

    public int Y { get; set; }
}

從構造函數中可以看出,我需要將值乘以10.無論如何都要在不刪除autoproperties的情況下執行此操作嗎?

我嘗試了以下不認為它導致遞歸,然后一切都變得富有

public int X { get {return X;} set{ X *= 10;} }

我想將值分配給X和Y乘以10。

Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 7 to X but I would like it to be 70.

為了使setter像這樣工作,你需要使用支持字段:

class Coordinates
{
    public Coordinates(int x, int y)
    {
        X = x;
        Y = y;
    }

    private int _x;
    public int X
    {
        get { return _x; }
        set { _x = value * 10; }
    }

    private int _y;
    public int Y
    {
        get { return _y; }
        set { _y = value * 10; }
    }
}

舉個例子:

Coordinates coords = new Coordinates(5, 6); // coords.X = 50 coords.Y = 60
coords.X = 7; // this gives 70

但是,我不建議你有這樣的二傳手,因為它可能導致混亂。 最好有一個專用的方法來進行這樣的乘法運算。 最后,您的代碼將更具描述性和直觀性。

你得到一個遞歸,因為你再次調用相同的屬性,而后者又調用相同的屬性,而后者又調用相同的屬性......你明白了。

public int X {get {return X ;} set { X * = 10;}}

汽車物業如何運作?
幕后屬性實際上是方法,這意味着它們實際上並不存儲數據。 那么誰保存數據? AutoProperties生成私有后端字段以保存數據。

所以在簡單的auto屬性聲明中

int X { get; set; }

編譯器將其轉換為類似的東西

private int <X>k__BackingField;

public int X
{
    [CompilerGenerated]
    get
    {
        return <X>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        <X>k__BackingField = value;
    }
}

因此,無論您將其用作自動屬性還是簡單屬性,它們都是相同的。

現在,回答你的問題,用釋義,“我如何將價值乘以10乘以”

您可以使用以下兩種方式解決它:1。將數據乘以10(setter實現)2。將數據乘以10(getter實現)

我不會詳細說明你應該使用哪一個,因為對於這種簡單的場景,兩者都是完全有效的。 我只想說,選擇的一些因素將是微觀(微觀微觀)性能,真正的狀態存儲。

這是setter實現

private int _x;
public int X
{
    get
    {
        return _x;
    }

    set
    {
        return _x*10;
    }
}

暫無
暫無

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

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