我最近向一位同事发了言:
永远不 应该明确捕获NullReferenceExceptions
我用了永远......嗯这个词.我自己从未见过适当的用例来抓住它们,但我想检查一下是否还有其他用户?
毕竟,从来没有这么强的话语.....
我正在寻找一种很好的方法来处理对象层次结构中的空引用.
即:
if(null == Object1.Object2.Object3.Property)
Run Code Online (Sandbox Code Playgroud)
如果说Object2为null,则此示例将抛出Null Reference异常.
在我的情况下,我不在乎什么是null,只是有些东西.我真的不想在我希望做这样的事情的每个地方放置尝试/捕获,所以我一直在寻找替代方案.
我试过了?? 运算符,但这会在两个级别之后产生一些难看的代码.
任何想法都赞赏.
我有一个null参数中的一个参数String.Format()调用抛出NullReferenceException.为什么即使参数不在结果字符串中也要进行检查?
class Foo
{
public Exception Ex { get; set; }
}
class Program
{
public static void Main(string[] args)
{
var f1 = new Foo() { Ex = new Exception("Whatever") };
var f2 = new Foo();
var error1 = String.Format((f1.Ex == null) ? "Eror" : "Error: {0}", f1.Ex.Message); // works
var error2 = String.Format((f2.Ex == null) ? "Eror" : "Error: {0}", f2.Ex.Message); // NullReferenceException
}
}
Run Code Online (Sandbox Code Playgroud)
除了两个被分隔的呼叫之外,还有其他解决方法if()吗?
.net c# exception-handling string-formatting nullreferenceexception
我有一个静态类,有几个静态方法.在这些方法中,我试图使用访问当前线程的上下文HttpContext.Current.例如:
var userName = HttpContext.Current.User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,我会收到一个NullReferenceException臭名昭着的"对象引用未设置为对象的实例".
有任何想法吗?
asp.net session static-methods httpcontext nullreferenceexception
我正在使用另一个开发人员创建的实体\表来处理WCF\EF时作为菜鸟的项目.我通常很快就能抓住新事物,而且我对如何使用datacontext在应用程序中完成工作有一些小的基础知识.我唯一的问题是,其他开发人员创建的上下文似乎不起作用,我不确定问题是模型,映射还是表.
这是项目的基本前提.开发人员首先创建数据库,然后使用这些对象的EF映射的POCO对象创建表.他这样做是为了确保以后使用较新的columns\tables轻松升级.在创建模型时,通过覆盖OnModelCreating事件并将映射添加到每个对象的模型构建器来替换映射而不是EF的映射.然后,接下来似乎发生的事情是NullReferenceException:
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.ValidateConsistency(NavigationPropertyConfiguration navigationPropertyConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(EdmNavigationProperty navigationProperty, EdmModel model, EntityTypeConfiguration entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociations(EdmEntityType entityType, EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EdmEntityType entityType, EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntities(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
Run Code Online (Sandbox Code Playgroud)
我的主要问题是,我似乎找不到任何可以通过搜索引起我的原因的信息,因为我似乎无法找到在这个特定方法中遇到此问题的其他人.我将包含映射\ POCOs \用法的代码片段,但我在这个项目的NDA下,我不知道扩展到什么程度.我的主要问题是,如果有人可以告诉我应该在哪个方面查找此问题的原因... POCO设置,映射设置或表设置?任何帮助将不胜感激!我已经多次查看了所有代码,但似乎无法发现任何事情,所以一些重点会有所帮助.我会尽力帮助.
有没有办法使下面的代码工作?
open System.Collections.Generic
type Geometry<'t>(child: 't) =
let values = List()
member o.add (v: float) = values.Add v; child
and Line() as self =
inherit Geometry<Line>(self)
member o.length v = o.add v
let line = Line().length(50.0)
Run Code Online (Sandbox Code Playgroud)
我明白了
System.NullReferenceException:未将对象引用设置为对象的实例.
编辑:
调用以下内容就足以触发异常.
let line = Line()
Run Code Online (Sandbox Code Playgroud)
动机是你可以做到:
let line = Line().x1(10).y1(20).x2(30).y2(10).color("blue") // ...
Run Code Online (Sandbox Code Playgroud)
你可以在所有几何中重复使用普通成员(圆形,椭圆形......)
此代码抛出页面查询字符串中未指定的NullReferenceExceptionif mode:
bool isAdvancedMode = Request.QueryString["mode"].Equals("advanced");
Run Code Online (Sandbox Code Playgroud)
这是我解决这个问题的方法:
bool isAdvancedMode = (Request.QueryString["mode"] + "").Equals("advanced");
Run Code Online (Sandbox Code Playgroud)
这是标准做法还是黑客攻击?
我是使用Xamarin.Android进行Android开发的新手,我想了解如何解决下一个问题.
有时,从后台恢复我的Android应用程序后,我面临的下一个错误:
Unable to find the default constructor on type MainMenuFragment.在MainMenuFragment使用应用程序NavigationDrawerActivity允许用户在应用程序中不同的片段之间切换.
为了解决这个问题,我MainMenuFragment在下一个链接中添加了一个默认构造函数:
public class MainMenuFragment : DialogFragment
{
readonly NavigationDrawerActivity navigationDrawer;
#region Constructors
public MainMenuFragment () {} // Default constructor...
public MainMenuFragment (NavigationDrawerActivity navigationDrawer, IMenuType launchMenu = null)
{
if (navigationDrawer == null)
throw new ArgumentNullException ("navigationDrawer");
this.navigationDrawer = navigationDrawer;
...
Fragment UpdateTopFragmentForCurrentMenu (Fragment newMenuRootFragment = null)
{
Fragment currentMenuRootFragment = navigationDrawer.CurrentFragment; // issued line.
Run Code Online (Sandbox Code Playgroud)但是现在在将来的某个时候,MainMenuFragment使用其默认构造函数初始化,并且在第一次尝试访问其navigationDrawer时,它会抛出System.NullReferenceException:
System.NullReferenceException: …Run Code Online (Sandbox Code Playgroud) 我想知道你是否可以在F#中添加类似"null-safe"-operator的东西.我知道可能有计划在C#中为这样一个运营商提供下一个更大的版本.
如果没有办法实现这样的行为,是否有办法包装一个可能会抛出一个NullReferenceException捕获异常并返回的块的语句null.
我想到了类似的东西:
let sth = %% <@ someobject.method().another().andAnother() @>
Run Code Online (Sandbox Code Playgroud)
其中%%是执行表达式并检查异常的自定义运算符.
我做的一个尝试是:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
let (~%%) (right:Expr) =
try
right.CompileUntyped()
right()
with
| ex -> null
Run Code Online (Sandbox Code Playgroud)
但这不符合我的要求(事实上它甚至没有编译:)
我通读了:
有没有人有想法如何优雅地为链式方法创建这样的单行try-catch?
f# exception-handling operator-overloading quotations nullreferenceexception
我正在重写我的类上的equals函数并且我得到一个零点异常,尽管我在调试器的"watch"部分输入相同的代码时没有异常.
这是我的代码(与==a 比较的是字符串或基本类型):
return this.workOrder == i.workOrder
&& this.upi == i.upi
&& this.testName == i.testName
&& BasicFunctions.ArraysEqual(this.testTrays, i.testTrays)
&& this.supplyVoltage == i.supplyVoltage
&& this.supplyAmperage == i.supplyAmperage
&& this.commandResults == null ? i.commandResults == null : this.commandResults.Equals(i.commandResults)
&& this.id == i.id;
Run Code Online (Sandbox Code Playgroud)
观察窗口中的视图:

比较commandResults是唯一可能导致null异常的东西,正如你可以从代码中看到的那样,这个场景应该由三元运算符处理.不仅如此,但在失败的情况下,它应该永远不会到达该部分,因为该行应该在第一个假部分停止执行.怎么会发生这种情况?
编辑: 这里要求的是异常的细节(请注意,这已由ArrayEquals函数调用,并且异常不在列出的代码中使用的异常内)
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="ATE"
StackTrace:
at ATE.Network.TestLocationListener.TestClientInformation.Equals(Object obj) in C:\Users\jdudley\git\ATE\ATE\ATE\Network\TestLocationListener.cs:line 85
at ATE.BasicFunctions.ArraysEqual[T](T[] a1, T[] a2) in C:\Users\jdudley\git\ATE\ATE\ATE\BasicFunctions.cs:line 150
at ATE_Remote_Controller.Form1.remoteClient1_StatusUpdated(Object sender) …Run Code Online (Sandbox Code Playgroud) c# ×4
.net ×3
asp.net ×2
f# ×2
exception ×1
httpcontext ×1
inheritance ×1
null ×1
poco ×1
query-string ×1
quotations ×1
session ×1