是否有這樣的可能?我假設不是,但它看起來不錯對我說:屬性支持值範圍
class MyClass {
public int Foo {
get { return m_foo; }
set {
// Bounds checking, or other things that prevent the use
// of an auto-implemented property
m_foo = value;
}
// Put the backing field actually *in* the scope of the property
// so that the rest of the class cannot access it.
private int m_foo;
}
void Method() {
m_foo = 42; // Can't touch this!
}
}
我當然知道這個語法是不正確的,這將無法編譯。爲了清晰地表達我的想法,這是假想的未來-C#。我對這個有點假設的問題表示歉意,但對程序員來說太具體了。
類似這樣的東西可以在編譯器中實現,它可以用於一個目的:只允許屬性的get
和set
訪問器查看字段,實質上允許該屬性是自包含的(作爲自動實現的屬性),而允許額外的獲取/設置邏輯。
這是一個簡單的是/否的問題(因爲那樣很** **無),或者你想替代解決這個‘問題’? –
我只是好奇你想通過這樣做達到什麼目的? –
備用解決方案將會非常有趣。強制使用屬性而不是類中的變量可能是一個很好的功能。因爲這一定是目標,對吧? –