哪些 C# 语言功能可以帮助您减少代码行并提高可读性?
我今天遇到了 ReSharper 提供的 C# 语言功能,ReSharper 是 ??操作员。这使得代码比我最初的尝试更加简洁。请参阅下面的迭代来改进代码的行数/长度/可读性。
第一次尝试可能类似于..
if (usersEmail == null)
userName = firstName;
else
userName = usersEmail;
重构为..
userName = usersEmail == null ? firstName : usersEmail;
最初我认为上面将是最有效/简洁的版本,但是还有第三步...
userName = usersEmail ?? firstName;
我想知道您是否有任何类似的示例,其中 C# 语言功能有助于减少代码行数并提高可读性?
I came across a C# language feature today courtesy of ReSharper, the ?? operator. This helped make the code even more concise than my initial attempt. See below for iteration in improving lines/length/readability of code.
A first attempt could be something like..
if (usersEmail == null)
userName = firstName;
else
userName = usersEmail;
Refactored to..
userName = usersEmail == null ? firstName : usersEmail;
Initially I thought the above would be the most efficient/concise version, but there is a third step...
userName = usersEmail ?? firstName;
Id like to know if you have any similar examples where C# language features help with reducing lines of code and improving readability?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
using 块、LINQ、匿名委托,这样的例子不胜枚举。C
# 有一个非常好的习惯,即在每个主要版本中引入功能,从而减少您必须编写的代码量。
the using block, LINQ, anonymous delegates, the list would just go on..
C# has a very nice habit of introducing features in every major release that cut down the amount of code that you have to write.
用于隐式静态类型和自动属性的 var 关键字是两个很好的例子。
The
var
keyword for implicit static typing and automatic properties are two good examples.该线程有很多精华:C# 的隐藏功能?(包括您提到的那个)
This thread has a lot of gems: Hidden Features of C#? (including the one you mentioned)
使用 using 关键字
Using using keyword
扩展方法。
Extension methods.
LINQ 查询允许您比 foreach 循环更好地表达查询条件
LINQ queries allowing you to express the query criteria better than a foreach loop