我正在尝试最大限度地减少此代码:
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;
还有其他类似的写法吗?
回答“还有其他类似的写法吗?”:
我不知道你是否考虑过这种“代码缩减”,但是怎么样……
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
还有另一种方法
data != null? data.IsReady = false:true;