這是一種聲明不可變結構的正確方法嗎?使用公共只讀字段爲不可變結構工作嗎?
public struct Pair
{
public readonly int x;
public readonly int y;
// Constructor and stuff
}
我想不出爲什麼會遇到問題,但我只是想問一下確認。
在這個例子中,我使用了整數。如果我使用了一個類,但是這個類也是不可變的,像這樣?這應該也可以,對嗎?
public struct Pair
{
public readonly (immutableClass) x;
public readonly (immutableClass) y;
// Constructor and stuff
}
(旁白:據我所知,使用性能更加普及,並允許改變,但這種結構的目的是從字面上只存儲兩個值我在永恆的問題只是有興趣在這裏。)
'readonly'性能/成員只能從構造函數(最晚)內。它們不能使用屬性初始化語法進行設置。 – 2011-05-19 18:32:09
你可能想檢查[不可變類型:瞭解他們的好處並使用它們](http://codebetter.com/patricksmacchia/2008/01/13/immutable-types-understand-them-and-use-them/) – YetAnotherUser 2011-05-19 18:34:56
'readonly'隻影響賦值操作符。它沒有C++的const關鍵字那樣強大的語義。 – 2011-05-19 18:47:52