这是一段代码:
IUser user = managerUser.GetUserById(UserId);
if ( user==null )
throw new Exception(...);
Quote quote = new Quote(user.FullName, user.Email);
Run Code Online (Sandbox Code Playgroud)
这里一切都很好.但是,如果我用以下内容替换"if"行:
ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);
Run Code Online (Sandbox Code Playgroud)
函数实现如下:
public abstract class ComponentException<T> : ComponentException
where T : ComponentException, new()
{
public static void FailIfTrue(bool expression, string message)
{
if (expression)
{
T t = new T();
t.SetErrorMessage(message);
throw t;
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
然后resharper生成一个警告:可能'System.NullReferenceException'指向'user'对象的第一次使用.
Q1.为什么会产生这种异常?据我所知,如果'user == null',那么将生成异常并且执行将永远不会到达使用点.
Q2.如何删除该警告?请注意:1.我不想用注释来抑制此警告(我将有很多类似的部分,并且不想在'评论的garbase中转换我的源代码); 2.我不想更改resharper设置以将此问题从警告更改为"提示"的"建议".
谢谢.
欢迎任何想法!
PS我正在使用resharper 5.1,MVSV 2008,C#
也许问这个问题背叛了我对这个过程缺乏了解,但话说回来,没有更好的理由要问!
跟踪这些可能会令人沮丧,因为堆栈跟踪可以帮助我知道从哪里开始查看,但不知道哪个对象为空.
引擎盖下发生了什么?是因为变量名称没有捆绑在可执行文件中吗?
好吧,几个月前我问了一个关于C和C++的类似问题,但由于整个"Windows Phone"的缘故,我最近一直在关注C#.
那么,在C#中,是否应该在方法边界检查NULL?我认为这与C和C++不同,因为在C#中,通常可以确定给定的引用是否有效 - 编译器将阻止在任何地方传递未初始化的引用,因此唯一剩下的可能错误是它为null .此外,在.NET Framework中为这些事物定义了一个特定的异常,即ArgumentNullException,它似乎编写了程序员认为在传递无效null时应该获得的异常.
我的个人意见再次表明,打电话的人打破了这个问题,而且打电话的人应该把NRE扔到他们面前,直到几天结束.但是,我对这方面的不太确定,而不是我在本地代码领域 - 在这方面,与C或C++相比,C#的编程风格完全不同.
那么......你应该在C#方法中检查空参数吗?
从最简单的案例开始.
如果我按下"文件 - >新项目 - > silverlight业务应用程序",它将打开MainPage.xaml,并在此帖子的底部附上消息.
它也对sourcesafe中存在的任何silverlight业务应用程序做了同样的事情 - 这是我个人第一次需要使用这项技术.
任何建议都非常感谢我真的需要开始一个项目,我觉得很残疾,没有设计师.
提前致谢.
发生了未处理的异常
单击此处重新加载设计器
细节:
System.NullReferenceException未将对象引用设置为对象的实例.在MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption()
的MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(标识符标识符)上的Microsoft.Windows.Design.Platform.SilverlightMetadataContext.SilverlightXamlExtensionImplementations.d__8.MoveNext()位于MS.Internal.Design.DocumentModel的MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement父级,PrefixScope parentScope,IParseContext上下文,IMarkupSourceProvider提供程序)的.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope,IParseContext context) Microsoft.Windows的Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem()上的MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem()中的.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) MS.Internal.Host.De的MS.Internal.Host.PersistenceSubsystem.Load()上的.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState()signer.Load()在MS.Internal.Designer.VSDesigner.Load()在MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load()在MS的MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView视图).在MS.Internal.Host.Isolation.IsolatedDesigner的MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory,IsolatedView视图)中的Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory,IsolatedView视图).在MS.Internal.Designer.DesignerPane.LoadDesignerView()上加载()
我希望有人可以帮我解决一个小小的谜团......
此代码正在生产中,并在那里工作.问题出现在我的localhost上(我正在测试我在发布到staging之前所做的更改). 这工作到2天前,我不知道它为什么会自发地停止工作.
(这是一个.NET 3.5 Web窗体应用程序)
我有一份可能已报告事件的"组织"列表.该列表从我的数据库中的Organization表填充.
<asp:DropDownList ID="Organizations" runat="server" Width="205" AutoPostBack="True" DataTextField="Name" DataValueField="Id"></asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)
这是绑定列表的代码:
Organizations.DataSource = _service.ListOrganizations()
.Where(o => o.IsDeleted == false && o.ReportedBy == true)
.OrderBy(o => o.Name);
Organizations.DataBind();
Organizations.Items.Insert(0, new ListItem("Please make a selection", "-1"));
// Find the "VICTIM...." items
ListItem victim = Organizations.Items.FindByText("VICTIM");
ListItem guardian = Organizations.Items.FindByText("VICTIM'S PARENT/GUARDIAN");
ListItem child = Organizations.Items.FindByText("VICTIM'S SON/DAUGHTER");
ListItem partner = Organizations.Items.FindByText("VICTIM'S SPOUSE/DOMESTIC PARTNER");
ListItem unknown = Organizations.Items.FindByText("UNKNOWN");
// Move the "VICTIM...." items to the top of the list, under …Run Code Online (Sandbox Code Playgroud) 我一直在为我的应用程序的几个版本使用相同的代码而没有任何问题,但我现在神秘地接受NullRerefenceException以下内容:
this.Loaded += delegate {
deleteBrush = new DeleteBrushAdorner( background );
AdornerLayer al = AdornerLayer.GetAdornerLayer( background );
al.Add( deleteBrush ); // null ref here??
};
Run Code Online (Sandbox Code Playgroud)
background只是一个Border元素.
我对可能导致它的原因的两点看法是:a)切换到.NET 4.0,以及b)将上述元素(即a)的实例UserControl放在一个ItemsControl.
奇怪的是,这并不是一直发生的,而且很难预测何时会发生,所以它不可靠.
我正在为MVC Web应用程序编写单元测试,并且我一直在获取null引用异常,因为模拟的测试对象只是部分初始化.我知道哪一行抛出异常,它看起来像这样:
return Supervisor.RegistrationInformation.Registrations
.Any(r =>
r.RegistrationCountry.IsUSAOrCandada() &&
(!DatesWorked.Start.HasValue || r.RegistrationDate <= DatesWorked.Start.Value) &&
(!DatesWorked.End.HasValue || r.RegistrationExpirationDate >= DatesWorked.End.Value) &&
//...
Run Code Online (Sandbox Code Playgroud)
那里有很多参考文献,其中任何一个都可能是问题所在.然而,NullReferenceException它本身似乎没有捕获哪个引用爆炸.我传入lambda的事实提出了另一个挑战:据我所知,我无法在调试期间单步执行lambda并查看哪些成员为rnull.
有什么方法可以做到以下一个或两个:
NullReferenceException?Any?我觉得必须有办法做这些事情,但我似乎无法找到它.我使用的是VS2010 Premium,我安装了Resharper,VS Power Tools和其他一些扩展程序.如果有一个附加组件可以做到这一点,我会很好.
正如Eric Lippert指出的那样,当代码在Release配置中编译时,无法确定NR异常的来源.我只是询问在调试模式下工作.如果Visual Studio(或VS的某些扩展)可以在调试时跟踪引用的来源,那将回答我的问题.
第二个问题 - 如何打破和逐步通过一个lambda - 已经得到了回答,但我仍然想知道是否有一种自动方法来追踪空引用.
我正在尝试确定Session变量是否存在,但我收到错误:
System.NullReferenceException:未将对象引用设置为对象的实例.
码:
// Check if the "company_path" exists in the Session context
if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null)
{
// Session exists, set it
company_path = System.Web.HttpContext.Current.Session["company_path"].ToString();
}
else
{
// Session doesn't exist, set it to the default
company_path = "/reflex/SMD";
}
Run Code Online (Sandbox Code Playgroud)
那是因为Session名称"company_path"不存在,但我无法检测到它!
目前我遇到的问题是,在服务中SAP Sybase SQL Anywhere随机抛出NullReference Exceptions,执行大量的SQL查询.始终在using块中创建连接并正确打开和关闭.没有很多并行连接,但一段时间后(随机)抛出以下异常:
异常:System.NullReferenceException:对象未设置为实例.bei iAnywhere.Data.SQLAnywhere.SAConnection.Dispose(布尔处理)bei iAnywhere.Data.SQLAnywhere.SAConnection.Close()bei iAnywhere.Data.SQLAnywhere.SAConnection.get_State()bei product.Framework.DAL.ConnectionManager.GetOpenPoolConnection [T ](String ModuleName,String Connection,Boolean resizePoolOnRimteOut,Int64 Time Out,Boolean isSecondTry)bei product.Framework.DAL.ORM.Sybase.SybaseStack.LoadDataFromDB [T](String where_part,String connectionStringName,Object [] sa_params)bei product. Framework.DAL.ORM.Sybase.SybaseStack.LoadData [T](String optWherePart,Object [] parameter)bei product.PlugIn.DocCenterClient.AS_Modules.DefaultInstanceDataExportModule.DoSingalProcessing()bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCt x)bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)bei System.Threadi ng.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state)bei System.Threading.ThreadHelper.ThreadStart()
有人知道这种行为是由什么引起的吗?我们无法弄清楚任何规律性.
编辑
打开和关闭连接时抛出异常.
编辑
我们SAP SQL Anywhere 12用作数据库引擎/服务器和SAP SQL Anywhere 16客户端组件.
编辑
using (SAConnection connection = DAL.ConnectionManager.GetOpenPoolConnection<SAConnection>())
{
var …Run Code Online (Sandbox Code Playgroud) 我们有一个属性,其工作是查找描述.如果查找失败,则应显示空字符串.
所以我们可以像这样对属性进行编码:
If foo.bar Is Not Nothing Then
Return foo.bar.Description
Else
Return String.Empty
End If
Run Code Online (Sandbox Code Playgroud)
但是这涉及到两次执行foo.bar,如果这样做很昂贵,那么它可能更好:
Dim b As bar = foo.bar
If b IsNot Nothing Then
Return b.Description
Else
Return String.Empty
End If
Run Code Online (Sandbox Code Playgroud)
但实际上我们想要做的就是将任何类型的错误视为空的描述.所以在某些方面这更简单:
Try
Return foo.bar.Description
Catch e As NullReferenceException
Return String.Empty
End Try
Run Code Online (Sandbox Code Playgroud)
但是,有没有问题(性能,纯度,其他?)只是捕捉和忽略错误?
你有时会认为抛出异常是昂贵的,但是我不确定作者是否意味着使用Throw关键字(我没有做的)构建异常是昂贵的,或者他是否意味着允许异常发生是很昂贵的(因为我会这样做).
c# ×7
asp.net ×2
debugging ×2
resharper ×2
.net ×1
.net-4.0 ×1
adorner ×1
adornerlayer ×1
arguments ×1
session ×1
silverlight ×1
sql ×1
sqlanywhere ×1
vb.net ×1
wpf ×1