gpt4 book ai didi

c# - 属性初始化和 'this'

转载 作者:行者123 更新时间:2023-12-02 16:02:09 26 4
gpt4 key购买 nike

我想知道是否可以使用对 this 关键字的引用来初始化一个(引用类型)属性(当它的值为 null 时),但是没有 使用构造函数。
在某些情况下,我不想使用构造函数来初始化属性,因此,如果没有人访问它,它的值将不会被创建。
此外,如果可能的话,我不喜欢将属性声明与其在构造函​​数中的初始化分开。

一个典型的例子是 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

最佳答案

这可以使用 null-coalescing assignment operator 来完成:

private Command addRecordCommand = null;
public Command AddRecordCommand
=> addRecordCommand ??= new Command(AddRecordCommandExecute);

仅当 addRecordCommand 为 null 时才分配给它,然后返回该字段的值。

关于c# - 属性初始化和 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70395852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com