当前位置: 首页 > 知识库问答 >
问题:

属性初始化和“this”

范稳
2023-03-14

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

一个典型的例子是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”在当前上下文中不可用

是否有一种方法可以像自动实现的属性提供的那样使用一行声明,但是访问<code>这个

共有3个答案

杨慎之
2023-03-14

我想出了一种方法来减少代码行,以及对私有成员的访问,使用这种技术:

private Command FAddRecordCommand = null;
public Command AddRecordCommand => LazyInitializer.EnsureInitialized(ref this.FAddRecordCommand, () => new Command(this.AddRecordCommandExecute));

private async void AddRecordCommandExecute()
{
    //do something
}

这里我使用了:

    < Li > lambda表达式< code>=

这样this关键字可用,声明只需要一行代码,我只访问私有成员一次。

将成员传递为ref允许更改其值,并且Func

如果您不喜欢属性声明的lambda表达式,您仍然可以在一行中声明它:

public Command AddRecordCommand { get { return LazyInitializer.EnsureInitialized(ref this.FAddRecordCommand, () => new Command(this.AddRecordCommandExecute)); } }

司马高韵
2023-03-14

看起来你正在寻找惰性初始化,你可以在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);
朱兴运
2023-03-14

这可以使用空合并赋值运算符完成:

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

仅当<code>addRecordCommand

 类似资料:
  • 但是我得到错误“在初始化之前使用属性”这是有道理的,因为我只声明。但是我不知道我应该如何或为了什么初始化输入,因为值是输入

  • 问题内容: 您将如何在Swift中实现以下模式? 所述类被初始化,其中包含的词典JSON数组。这些字典用于初始化类。但是,当访问或属性时,对象的初始化会延迟进行。 问题答案: 看来这个问题已经得到了很大的回答,但是回过头来看原始帖子,这是(IMHO)Swift中相对简洁的翻译。关键是您可以链接惰性属性。请注意,我同时使用了类函数和闭包- 两者都很好。

  • 本文向大家介绍iOS 在didSet中初始化属性,包括了iOS 在didSet中初始化属性的使用技巧和注意事项,需要的朋友参考一下 示例 也可以设置一个值并对其进行初始化:            

  • Json服务器数据显示,在使用retrofit2和rxjava2的android中,当参数传递给inteface时,会出现错误。 接口

  • 我不知道这是怎么回事 主要活动 我遇到了这个问题 2022-03-18 09:18:27.393 13874-13874/com。实例githubuser2 E/AndroidRuntime:致命异常:主进程:com。实例githubuser2,PID:13874 java。lang.RuntimeException:无法启动活动组件信息{com.example.githubuser2/com.e

  • 我有一个类,我注入到ViewModel ViewModel工厂,当在活动中的onCreate方法中初始化视图模型时,它说传递的值没有初始化。 下面是我的代码 我对Kotlin很陌生,所以尝试过调试,但在这个问题上卡住了。 这是Mainactive代码: 我的ViewModelFactory: 我的班级回购: 这是我收到的错误: