这比 Null Coalesce 运算符好在哪里?
我遇到了这个< /a> 今天的博客文章。
我来总结一下。博主评论这段代码,说它很难看。
// var line1 = person.Address.Lines.Line1 ?? string.Empty;
// throws NullReferenceException:
// {"Object reference not set to an instance of an object."}
// The ugly alternative
var line1 = person.Address == null
? "n/a"
: person.Address.Lines == null
? "n/a"
: person.Address.Lines.Line1;
然后博主继续编写一个类,允许您用新的语法替换上面的代码。
var line2 = Dis.OrDat<string>(() => person.Address.Lines.Line2, "n/a");
Dis 类的代码如下。
public static class Dis
{
public static T OrDat<T>(Expression<Func<T>> expr, T dat)
{
try
{
var func = expr.Compile();
var result = func.Invoke();
return result ?? dat; //now we can coalesce
}
catch (NullReferenceException)
{
return dat;
}
}
}
所以我的第一个问题是为什么包含 ??
的原始代码必须替换为看起来该死的 ?:
代码。
我的第二个问题是为什么使用表达式树而不是空合并?我能想到的唯一原因是因为他们使用了延迟初始化,但这从帖子中并不清楚,从博文中的测试代码也不清楚。我也会在这里发布。
顺便说一句,有人知道如何创建固定大小的代码块窗口吗?或者这里更喜欢非滚动代码块?我在元博客中没有看到任何内容。
I ran into this blog post today.
I'll summarize. The blogger is commenting on this code and saying it was ugly.
// var line1 = person.Address.Lines.Line1 ?? string.Empty;
// throws NullReferenceException:
// {"Object reference not set to an instance of an object."}
// The ugly alternative
var line1 = person.Address == null
? "n/a"
: person.Address.Lines == null
? "n/a"
: person.Address.Lines.Line1;
The blogger then goes on to write a class that allows you to replace above code with a new syntax.
var line2 = Dis.OrDat<string>(() => person.Address.Lines.Line2, "n/a");
The code for the Class Dis is as follows.
public static class Dis
{
public static T OrDat<T>(Expression<Func<T>> expr, T dat)
{
try
{
var func = expr.Compile();
var result = func.Invoke();
return result ?? dat; //now we can coalesce
}
catch (NullReferenceException)
{
return dat;
}
}
}
So the first question I have is why would the original code containing ??
have to be replaced with the accursed looking ?:
code.
My second question is why use the expression tree over the Null Coalesce? The only reason I can think of it is because they are using lazy initialization, but that is not clear from the post, nor is it clear from the test code, which is in the blogpost. I'll post that here as well.
BTW, anyone know how to create a fixed sized code block window? Or is a non scrolling codeblock prefered here? I didn't see anything in the Meta blog.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我看不出有任何理由在博客示例中使用表达式树,Func 就足够了。
我的建议是使用 Maybe* monad 实现,而不是该代码。参见示例。
你的代码变成:
[*] 这不是真正的 monad,而是它的一个非常简化的版本。
I do not see any reason to use expression trees in blogged sample, Func is enough there.
My suggestion is using Maybe* monad iplementation, instead of that code. See example.
And your code becomes:
[*] This is not actual monad, but a very simplified version of it.
代码是博客更糟糕。方法名称
Dis.OrDat
很难看,并且没有描述该方法实际执行的操作。使用
Expression
是多余的,可能只是:他立即依次调用
Compile
和Invoke
,所以他实际上并没有对表达式树做任何事情。按原样传入Func
是一样的,没有编译Func
的开销。但更糟糕的是,代码使用流量控制异常,这总是不好的:
人.Address
属性似乎是可选的,因此它为空并不是“异常”,因此使用它的代码不应引发异常。上面的catch
无法区分person.Address == null
和Address
属性 getter 的实现在内部被破坏,导致>NullReferenceException 被抛出。它只是将它们全部吞噬。
因此,总的来说,我很乐意忽略这篇博文。
The code is the blog is worse. A method name
Dis.OrDat
is ugly, and doesn't describe what the method actually does.The use of an
Expression<T>
is redundant, it could just be:He calls
Compile
andInvoke
one after another right away, so he doesn't actually do anything with the expression tree. Passing in theFunc<T>
as is would be the same, without the overhead of compiling theFunc
.But worse, the code uses exceptions for flow control, which is always bad: the
person.Address
property appears to be optional, so it isn't "exceptional" for it to be null, so an exception shouldn't be thrown by code which uses it. Thecatch
above can't distinguish betweenperson.Address == null
and the implementation of theAddress
property getter being broken internally causing anNullReferenceException
to be thrown. It just swallows them all.So, overall, I'd be happy to disregard the blog post.
为了保护这段代码:
不抛出 NullReferenceException
我会简单地使用:
而不是博客这个或那个(Dis.OrDat),
To protect this code:
from throwing NullReferenceException
I would simply use:
rather than the Bloggers this or that (Dis.OrDat),
第一行代码(
var line1 = person.Address.Lines.Line1 ?? string.Empty
)的问题是,如果 person、Address 或 Lines 为 null,则会抛出错误。空合并运算符仅作用于整个表达式的结果。这是一个相当优雅的解决方案,但在我开始在我的代码中使用它之前,我想检查一下表达式树的性能如何(但这只是因为我过去过度使用反射,然后才知道它是什么狗) )
the problem with the first line of code (
var line1 = person.Address.Lines.Line1 ?? string.Empty
) is that it will throw an error if person, Address or Lines is null. The null coalescing operator is only working on the result of the entire expression.It's a fairly elegant solution but I'd want to check what the performance of expression trees was like before I started sprinkling this through my code (but only because I got bit by overuse of reflection in the past before I knew what a dog it was)
对于你的第一个问题,有问题的代码:
var line1 = person.Address.Lines.Line1 ?? string.Empty;
如果
person
、Address
或Lines
为将抛出
NullReferenceException
>空。使用三元 if 语句的替换代码可以防止出现这种情况。 null 合并运算符仅对Line1
属性进行操作,因此它无法防止表达式的其余部分为null
。对于第二个问题,使用表达式树的原因可能是为了“简化”确保可以评估整个表达式所需的代码。虽然代码可以工作,但我认为它引入了一层并不真正必要或不需要的复杂性和开销。
For your first question, the code in question:
var line1 = person.Address.Lines.Line1 ?? string.Empty;
will throw a
NullReferenceException
ifperson
,Address
, orLines
isnull
. The replacement code using the ternary if statements protects against that case. The null coalescing operator will only operate on theLine1
property, so it can't protect against the rest of the expression beingnull
.For your second question, the reason for using the expression tree is probably to "simplify" the code required to ensure the entire expression can be evauluated. While the code would work, I think it introduces a layer of complexity and overhead that isn't really necessary or needed.
对于那些查看此条目但使用 C# 6.0(或更高版本)的人,代码现在可以使用空传播,并编写如下:
var line1 = person?.Address?.Lines? .Line1 ?? “不适用”;
For those looking at this entry but using C# 6.0 (or higher), the code can now use Null Propagation, and be written as follows:
var line1 = person?.Address?.Lines?.Line1 ?? "n/a";