为了彻底解释,这个问题已经过彻底检查。
我注意到 C# 6.0 中空传播运算符的一个似乎很差的限制,因为您不能针对已传播空的对象调用属性设置器(尽管您可以针对已传播空的对象调用属性获取器) . 正如您将从生成的 IL (我已反映到 C#)中看到的那样,没有什么可以限制使用 null 传播调用属性设置器的能力。
首先,我创建了一个简单的类,它具有 Java 样式的 Get/Set 方法和一个具有公共 getter/setter 访问权限的属性。
public class Person
{
public Person(string name, DateTime birthday)
{
Name = name;
}
public string Name { get; set; }
public void SetName(string name)
{
Name = name;
}
public string GetName()
{
return Name;
}
}
我已经在下面的测试类中测试了 null 传播的能力。
public class Program
{
public static void Main(string[] args)
{
Person person = new Person("Joe Bloggs", DateTime.Parse("01/01/1991"));
// This line doesn't work - see documented error below
person?.Name = "John Smith";
person?.SetName("John Smith");
string name = person?.Name;
}
}
赋值的左侧必须是变量、属性或索引器。
然而,您可能会注意到,通过调用设置名称的 Java 方法是SetName(...)
有效的,您可能还会注意到获取空传播属性的值也有效。
让我们看一下从这段代码生成的 C#:
public static void Main(string[] args)
{
Person person = new Person("Joe Bloggs", DateTime.Parse("01/01/1991"));
if (person != null)
{
person.SetName("John Smith");
}
string arg_33_0 = (person != null) ? person.Name : null;
}
请注意,当用于SetName
方法时,空传播转换为简单的if
语句,而当用于Name
属性 getter 时,使用三元运算符来获取Name
or的值null
。
我在这里注意到的一件事是使用if
语句和使用三元运算符之间的行为差异:使用 setter 时,使用if
语句会起作用,而使用三元运算符则不会。
public static void Main(string[] args)
{
Person person = null;
if (person != null)
{
person.Name = "John Smith";
}
person.Name = (person != null) ? "John Smith" : null;
}
在此示例中,我同时使用if
语句和三元运算符来检查 person 是否null
在尝试分配其Name
属性之前。该if
语句按预期工作;正如预期的那样,使用三元运算符的语句失败
你调用的对象是空的。
在我看来,限制来自于 C# 6.0 将 null 传播转换为if
语句或三元表达式的能力。如果它被设计为仅使用if
语句,则属性分配将通过空传播工作。
到目前为止,我还没有看到一个令人信服的论点来说明为什么这不应该发生,因此我仍在寻找答案!