因此,有一个合并运算符??
允许方便地处理空对象(IE。MyDisplayString = MyString ?? "n/a";
)
但是有一个很好的花哨的运算符来处理对象属性的类似情况吗?例如,假设您感兴趣的属性是属性的属性,如:MyDataObject.MySubModel.MyProperty
如果MyProperty
为空,则需要合并为“不适用”。您可以在此处使用??
,但如果MyDataObject
为空或MyDataObject.MySubModel
,该怎么办?
在尝试获取元素的可选属性和元素时,也会出现这种情况。 IE:MyString = MyElement.Attribute("MyOptionalAttribute").Value ?? "n/a";
如果属性不存在则失败。
处理这种情况有一种很好的方式吗?
答案 0 :(得分:6)
是否有一种很好的处理方式 这个场景?
You are not the first one要求this feature。一种方法是编写a "With" extension method来获取属性值,因为扩展方法可以处理在空引用上调用。而不是
thing.Foo.Bar
你会写
thing.With(x => x.Foo).With(x => x.Bar)
答案 1 :(得分:3)
在C#5及以下,如其他答案中所述,您需要自己构建一些东西。我们使用Helper而不是像其他人一样使用Extension方法,我们称之为NN,因为我们使用它很多,特别是在Razor中。
public static TValue N<TParent, TValue>(TParent o, Func<TParent, TValue> accessor, TValue defaultValue)
{
if (o == null)
return defaultValue;
return accessor(o);
}
/// <summary>
/// Guarantees return of null or value, given a prop you want to access, even if the parent in the first argument
/// is null (instead of throwing).
///
/// Usage:
///
/// NN.N(myObjThatCouldBeNull, o => o.ChildPropIWant)
/// </summary>
/// <returns>The value of the prop. Null if the object is null, or if the child prop is null.</returns>
public static TValue N<TParent, TValue>(TParent o, Func<TParent, TValue> accessor)
where TValue : class
{
return NN.N(o, accessor, null);
}
We actually use a few helpers depending on the desired behavior when null is encountered;例如,您可能正在访问一个int属性并想要0.链接Gist中的完整代码。
In C# 6, you can use the null property coalescence operator:
myObjThatCouldBeNull?.ChildPropIWant
更多信息:
答案 2 :(得分:2)
Null对象是一个对象 定义中性(“null”)行为
可以帮助您避免此问题。
另一种选择是使用extension methods,然后你可以说:
if (Contract
.NullSafe(c => c.Parties)
.NullSafe(p => p.Client)
.NullSafe(c => c.Address) != null)
{
// do something with the adress
Console.Writeline(Contract.Parties.Client.Adress.Street);
}
答案 3 :(得分:2)
正如我在此处所说:
Shortcut for "null if object is null, or object.member if object is not null"
这是一个相当频繁要求的功能,它没有成为C#4的标准。我们会考虑它的假设未来版本的语言,但它在优先级列表上并不高,所以我不会抱太大希望如果我是你。
答案 4 :(得分:0)
可能有一种更好或更优雅的方式来处理你所描述的问题,但我发现通常我必须在整个过程中检查空值,即:
MyString = MyElement.Attribute("MyOptionalAttribute") != null ? MyElement.Attribute("MyOptionalAttribute").Value : "n/a";
答案 5 :(得分:0)
对于XElement / XAttribute,您可以使用explicit conversion operators:
string myString = (string)myElement.Attribute("MyOptionalAttribute") ?? "n/a";
对于一般情况,“安全解除引用运算符”是fairly frequently requested feature。