NTB*_*ddy 18 c# resharper null
在我的函数的顶部,我正在尝试最好的方法来处理在C#中进入我的过程的null.检查和处理null的最佳方法是什么?为什么?我已经添加了我正在使用的完整代码,Resharper告诉我使用选项#1.通常我按照它说的做,因为我理解为什么它会使它更有效率.这次虽然我不确定所以我必须问.
Option #1
if (sender == null) return;
// Code goes here
or
Option #2
if (sender != null)
{
// Code goes here
}
Complete Code
private void EmployeeMouseHoverToolTip(object sender, EventArgs e)
{
if (sender != null)
{
var sUserIdentifier = ((C1TextBox)sender).Text;
var userIdentifier = Guid.Empty;
if (Utilities.IsGuid(sUserIdentifier))
{
userIdentifier = new Guid(sUserIdentifier);
}
var toolTipText = Utilities.UserIdentifierToName(userIdentifier);
c1SuperTooltip.SetToolTip(sender as C1TextBox, toolTipText);
}
}
Run Code Online (Sandbox Code Playgroud)
Kon*_*lph 43
最好的代码是禁止null(而不是你正在做的事情).这并不总是可行的(有时null以有意义的方式处理是很重要的) - 但在大多数情况下都是如此.
然后你需要做的就是(在防御性编码中)添加一个null检查并抛出异常:
if (arg == null)
throw new ArgumentNullException("arg");
Run Code Online (Sandbox Code Playgroud)
.NET框架和良好库中的许多(如果不是大多数)方法都是这样做的.
除此之外,sender事件永远不应该是null,我会说检查它是多余的.如果null传递给此事件,则代码会出现严重错误.
你处理的方式null(通过静默吞咽它并且什么也不做)可能会掩盖应用程序中的严重错误,并且很少(如果有的话)适当.代码中的错误应引起可疑行为,而不是席卷地毯.
在我看来,resharper正在建议选项1,因为它使得更容易阅读代码.你最终得到:
就性能而言,可能差别不大(尽管对您来说很重要,但要测量它).无论如何,没有什么可以阻止JIT编译器将一个表单重写到另一个表单,如果他们无法通过C#编译器输出相同的MSIL.
这是一个事件处理程序,它只应由控件调用以响应事件(从不直接由您自己的代码),因此您不应该关心空检查甚至是对sender参数进行类型检查(如果您只附加此事件)处理程序到同一类型的控件).我会这样做:
private void EmployeeMouseHoverToolTip(object sender, EventArgs e) {
var txtBox = (C1TextBox)sender;
var sUserIdentifier = txtBox.Text;
var userIdentifier = Utilities.IsGuid(sUserIdentifier) ?
new Guid(sUserIdentifier) :
Guid.Empty;
var toolTipText = Utilities.UserIdentifierToName(userIdentifier);
c1SuperTooltip.SetToolTip(txtBox, toolTipText);
}
Run Code Online (Sandbox Code Playgroud)
实际上,我更进一步,将逻辑分离,从逻辑中获取工具提示文本,以便读取和更新UI.像这样的东西:
private void EmployeeMouseHoverToolTip(object sender, EventArgs e) {
var txtBox = (C1TextBox)sender;
var toolTipText = ResolveUpdatedTooltipText(txtBox.Text);
c1SuperTooltip.SetToolTip(txtBox, toolTipText);
}
private string ResolveUpdatedTooltipText(string sUserIdentifier) {
var userIdentifier = ResolveGuid(sUserIdentifier);
return Utilities.UserIdentifierToName(userIdentifier);
}
private Guid ResolveGuid(string sUserIdentifier) {
return Utilities.IsGuid(sUserIdentifier) ?
new Guid(sUserIdentifier) :
Guid.Empty;
}
Run Code Online (Sandbox Code Playgroud)
因此,您不应使用您提供的任何选项.
如果你得到空值,你已经将处理程序添加到了你不应该拥有的东西中.如果其他一些bug导致它,你应该使用WinForms的全局异常处理程序处理它,这样程序就不会轰炸,记录它,并将日志上传到你的站点,无论你怎样检查这些错误.
| 归档时间: |
|
| 查看次数: |
2455 次 |
| 最近记录: |