如果我可以null使用對this關鍵字的參考而不使用建構式來初始化(參考型別)屬性(當它的值為),我正在徘徊。
在某些情況下,我不想使用建構式來初始化屬性,因此,如果沒有人訪問它,則不會創建其值。
此外,如果可能的話,我不喜歡將屬性宣告與其在構造函??數中的初始化分開。
一個典型的例子是 MVVM 模式編程的命令宣告:
private Command FAddRecordCommand = null;
public Command AddRecordCommand
{
get
{
if (this.FAddRecordCommand == null)
{
this.FAddRecordCommand = new Command(this.AddRecordCommandExecute);
}
return this.FAddRecordCommand;
}
}
private async void AddRecordCommandExecute()
{
//do something
}
我不喜歡寫三遍FAddRecordCommand會員的名字...
我嘗試使用自動實作的屬性,但this在初始化中無法訪問該關鍵字:
public Command AddRecordCommand { get; } = new Command(this.AddRecordCommandExecute);
編譯器拋出錯誤:關鍵字“this”在當前背景關系中不可用
有沒有辦法像 Auto-Implemented 屬性提供的那樣使用單行宣告,但可以訪問this?
uj5u.com熱心網友回復:
這可以使用空合并賦值運算子來完成:
private Command addRecordCommand = null;
public Command AddRecordCommand
=> addRecordCommand ??= new Command(AddRecordCommandExecute);
addRecordCommand僅當它為空時才分配給,然后回傳該欄位的值。
uj5u.com熱心網友回復:
似乎您正在尋找 可以在LazyInitializer的幫助下實作的延遲初始化
// Eager command creation
private Command AddRecordCommandExecute() {
//TODO: put the right creation and initialization code here
return new Command(this.AddRecordCommandExecute);
}
// Backing Field
private Command FAddRecordCommand;
// Lazy initialized property:
// AddRecordCommandExecute() will be run once
// on the first AddRecordCommand read
public Command AddRecordCommand => LazyInitializer
.EnsureInitialized(ref FAddRecordCommand, AddRecordCommandExecute);
uj5u.com熱心網友回復:
我想出了一種方法來減少代碼行數,以及使用這種技術對私有成員的訪問:
private Command FAddRecordCommand = null;
public Command AddRecordCommand => LazyInitializer.EnsureInitialized(ref this.FAddRecordCommand, () => new Command(this.AddRecordCommandExecute));
private async void AddRecordCommandExecute()
{
//do something
}
我在這里使用:
=>用于替換get屬性功能的lambda 運算式ref傳遞對FAddRecordCommand成員的參考以允許更改其值的關鍵字- 一個 lambda 函式,
() => new ???用于回傳初始化所需的新值 - 用于分配初始化值的LazyInitializer.EnsureInitialized方法(感謝Dmitry Bychenko的建議)
這樣this關鍵字就可用了,宣告只需要一行代碼,我只訪問私有成員一次。
傳遞成員 asref允許更改其值,并且Func<TProp>僅當初始值為 時才允許創建新值null。
如果你不喜歡 lambda 運算式的屬性宣告,你仍然可以在一行中宣告它:
public Command AddRecordCommand { get { return LazyInitializer.EnsureInitialized(ref this.FAddRecordCommand, () => new Command(this.AddRecordCommandExecute)); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389202.html
下一篇:來自回呼的狀態更新
