我有一堆看起来像这样的重复代码:
If mValue is Nothing Return ""
Return mValue.ToUpper
我定义了以下扩展方法来减少重复代码:
<System.Runtime.CompilerServices.Extension()>
Public Function EmptyIfNull(this As String) As String
If String.IsNullOrEmpty(this) Then Return ""
Return this
End Function
重复的代码可以重写为:
Return mValue.EmptyIfNull.ToUpper
这有缺点吗?
最佳答案
唯一的缺点是您实际上是在重新创建语言中已有的内容(空合并运算符,或 If function,因为它已在 VB.NET 中实现)
Return If(mValue, "").ToUpper()
应该做你正在寻找的。p>
至于您的扩展方法,无需调用 String.IsNullOrEmpty
, 因为你只需要处理它是 Nothing
的情况.
关于.net - 定义此扩展方法的缺点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536740/