为什么这个表达式在 C# 中无效? [已关闭]

问题描述 投票:0回答:2

我正在尝试最大限度地减少此代码:

if (data != null)
   data.IsReady = false;

当然,我可以用一行写出来:

if (data != null) data.IsReady = false;

但是我试图减少代码,所以我想知道为什么这无效:

//Compiler error CS0131: The left-hand side of an assignment must be a variable, property or indexer
data?.IsReady = false;

还有其他类似的写法吗?

c# operators
2个回答
1
投票

回答“还有其他类似的写法吗?”:

我不知道你是否考虑过这种“代码缩减”,但是怎么样……

using System;
                    
public class Program
{
    public static void Main()
    {
        Data d = null;
        d.SetReady(true);
        d = new Data();
        d.SetReady(true);
    }
}

public static class DataExtensions
{
    public static void SetReady(this Data data, bool value)
    {
        if(data is {}) data.IsReady = value;
      // C# 9: if(data is not null)
    }
}

public class Data
{
    public bool IsReady {get; set;}
}

曾在 dotnetfiddle 工作:https://dotnetfiddle.net/jiaVBp


-2
投票

还有另一种方法

data != null? data.IsReady = false:true;
© www.soinside.com 2019 - 2024. All rights reserved.