标签: nullreferenceexception

什么是NullReferenceException,我该如何解决?

我有一些代码,当它执行时,它抛出一个NullReferenceException,说:

你调用的对象是空的.

这是什么意思,我该怎么做才能解决这个错误?

.net c# vb.net null nullreferenceexception

1876
推荐指数
24
解决办法
127万
查看次数

检查C#中的对象是否为null

我想阻止对象的进一步处理,如果它是null.

在下面的代码中,我通过以下任一方法检查对象是否为null:

if (!data.Equals(null))
Run Code Online (Sandbox Code Playgroud)

if (data != null)
Run Code Online (Sandbox Code Playgroud)

不过,我收到NullReferenceExceptiondataList.Add(data).如果对象为null,则它应该永远不会进入if-statement!

因此,我问这是否是检查对象是否为null的正确方法:

public List<Object> dataList;
public  bool AddData(ref Object data)
    bool success = false;
    try
    {
        // I've also used "if (data != null)" which hasn't worked either
        if (!data.Equals(null))
        {
           //NullReferenceException occurs here ...
           dataList.Add(data);
           success = doOtherStuff(data);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return success;
}
Run Code Online (Sandbox Code Playgroud)

如果这是检查对象是否为null的正确方法,那么我做错了什么(如何防止对对象进一步处理以避免NullReferenceException)?

c# null nullreferenceexception

196
推荐指数
11
解决办法
78万
查看次数

为什么找到类型的初始值设定项会抛出NullReferenceException?

这让我很难过.我试图为Noda Time优化一些测试,我们在那里进行了一些类型的初始化程序检查.在将所有内容加载到新内容之前,我想我会发现一个类型是否具有类型初始化程序(静态构造函数或带有初始化程序的静态变量)AppDomain.令我惊讶的是,NullReferenceException尽管我的代码中没有空值,但对此进行了一次小测试.它只有当没有调试信息编译抛出异常.

这是一个简短但完整的程序来演示问题:

using System;

class Test
{
    static Test() {}

    static void Main()
    {
        var cctor = typeof(Test).TypeInitializer;
        Console.WriteLine("Got initializer? {0}", cctor != null);
    }    
}
Run Code Online (Sandbox Code Playgroud)

以及编译和输出的记录:

c:\Users\Jon\Test>csc Test.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17626
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.


c:\Users\Jon\Test>test

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at System.RuntimeType.GetConstructorImpl(BindingFlags bindingAttr, Binder bin
der, …
Run Code Online (Sandbox Code Playgroud)

.net reflection typeinitializer nullreferenceexception .net-4.5

193
推荐指数
2
解决办法
7757
查看次数

"对象引用未设置为对象的实例"是什么意思?

我收到此错误,我不确定这是什么意思?

你调用的对象是空的.

.net nullreferenceexception

182
推荐指数
5
解决办法
127万
查看次数

C#优雅的方法来检查属性的属性是否为null

在C#中,假设您希望在此示例中从PropertyC中提取值,而ObjectA,PropertyA和PropertyB都可以为null.

ObjectA.PropertyA.PropertyB.PropertyC

如何使用最少量的代码安全地获取PropertyC?

现在我会检查:

if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
    // safely pull off the value
    int value = objectA.PropertyA.PropertyB.PropertyC;
}
Run Code Online (Sandbox Code Playgroud)

做更像这样的事情会很好(伪代码).

int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;
Run Code Online (Sandbox Code Playgroud)

可能甚至进一步崩溃与空合并运算符.

编辑最初我说我的第二个例子就像js,但是我把它改成了psuedo-code,因为它被正确地指出它在js中不起作用.

c# nullable nullreferenceexception null-conditional-operator

87
推荐指数
10
解决办法
8万
查看次数

为什么将类型对象的动态类型转换为抛出空引用异常的对象?

我有以下功能:

public static T TryGetArrayValue<T>(object[] array_, int index_)
{
    ... //some checking goes up here not relevant to question

    dynamic boxed = array_[index_];
    return (T)boxed;
}
Run Code Online (Sandbox Code Playgroud)

当我用以下方式调用它时,

object a = new object();
object v = TUtils.TryGetArrayValue<object>(new object[] { a }, 0);
Run Code Online (Sandbox Code Playgroud)

(T)boxed 抛出空引用异常.

除了"对象"之外,我放在那里的任何其他类型,它完全正常.
任何想法是什么,为什么它抛出异常?

编辑:我使用动态的原因是为了避免在转换类型时出现异常,例如:

double a = 123;
int v = TUtils.TryGetArrayValue<int>(new object[] { a }, 0);
Run Code Online (Sandbox Code Playgroud)

.net c# dynamic nullreferenceexception

62
推荐指数
3
解决办法
2131
查看次数

我是如何在构造函数之后立即得到此NullReferenceException错误的?

我已经在我们的内联网上运行了几个星期的asp.net网站.我收到了来自我的application_error电子邮件发送方法的电子邮件,其中包含未处理的异常.

这是(我已经清理了一些路径以使其更好地显示)

例外:对象引用未设置为对象的实例.堆栈跟踪:位于System.Collections.Generic.Dictionary`2.Insert(TKey键,TValue值,布尔加法)的System.Collections.Generic.Dictionary`2.Add(TKey键,TValue值)位于TimesheetDomain.DataMappers.StaffMemberData TimesheetDomain\DataMappers\StaffMemberData.cs中的.ReadStaff(SqlDataReader reader):第362行

在TimesheetDomain\DataMappers\StaffMemberData.cs中的TimesheetDomain.DataMappers.StaffMemberData.GetStaffMember(String name):第401行

在TimesheetDomain\ServiceLayer\TimesheetManager.cs中的TimesheetDomain.ServiceLayer.TimesheetManager.GetUserFromName(String name):第199行

位于\ App_Code\UserVerification.cs中的UserVerification.GetCurrentUser():位于\ WebTimesheets\WebTimesheets.master.cs中的WebTimesheets.OnInit(EventArgs e)第29行:第159行

System.Web.UI.Page.ProcessRequestMain上的System.Web.UI.Control.InitRecursive(Control namingContainer)中的System.Web.UI.Control.InitRecursive(Control namingContainer)(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)

基本上它看起来像我的ReadStaff方法错误,它读取数据读取器来构建人员成员对象.这是一些代码:

while (reader != null && reader.Read())
{
    StaffMember newMember = null;
    string firstName = reader["FirstName"].ToString();
    string lastName = reader["LastName"].ToString();
    int staffID = (int)reader["StaffID"];
    int employSection = (int)reader["EmploySection"];
    StaffType employType = (StaffType)employSection;
    string emailAddress = reader["EmailInt"].ToString();
    int employCode = (int)reader["ibbwid"];

    //check if they are an admin staff member 
    if (IsAdminStaff(employType))
    {
        newMember = new AdminOfficer(firstName, lastName, employType, staffID, emailAddress, employCode);
    }
    else …
Run Code Online (Sandbox Code Playgroud)

c# asp.net nullreferenceexception

53
推荐指数
2
解决办法
2万
查看次数

为什么[Owin]在新项目上抛出空例外?

我有一个相当奇怪的问题,我不知道如何解决或者我是否能解决它.

我已经对这个问题进行了一些研究,但无法找到导致问题的答案.

我正在http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-并遵循一个相当简单的指南-openid点登录

启用SSL并更改controller为要求https后,我收到以下错误:

'/'应用程序中的服务器错误.

你调用的对象是空的.

描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例.

来源错误:

在执行当前Web请求期间生成了未处理的异常.可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息.

堆栈跟踪:

[NullReferenceException:对象引用未设置为对象的实例.]
Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider.Exception(CookieExceptionContext context)+49
Microsoft.Owin.Security.Cookies.d__2.MoveNext()+3698 System.Runtime .CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()+24 Microsoft.Owin.Security.Infrastructure. d__0.MoveNext()810个System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext()+ 427 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(T 请求任务)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+ 21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()+641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)+93
System. Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.AspNet.Identity.Owin.d__0.MoveNext()641系统.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21 Microsoft.Owin.Host.SystemWeb. IntegratedPipeline.d__5.MoveN EXT()287个System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务task)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务task)+52 System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21微软. Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()+272 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()+22 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()+33 Microsoft.Owin.Host .SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)+150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)+42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&completedSynchronously)+155

版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.34237

关闭SSL修复这个问题,我也知道,注释掉startup.authapp_start修复的问题SSL …

c# nullreferenceexception owin

50
推荐指数
4
解决办法
1万
查看次数

如何解决未将对象引用设置为对象的实例.

在我的asp.net程序中.我设置了一个受保护的列表.我在list中添加了一个值.但它显示对象引用未设置为对象错误的实例

protected List<string> list;
protected void Page_Load(object sender, EventArgs e)
{
     list.Add("hai");
}
Run Code Online (Sandbox Code Playgroud)

如何解决这个错误?

c# asp.net nullreferenceexception

44
推荐指数
2
解决办法
47万
查看次数

使用VB.NET IIF我得到NullReferenceException

我正在做一些调试,所以我想记录eventArgs值

我有一个基本上做的简单线:

logLine = "e.Value: " + IIf(e.Value Is Nothing, "", e.Value.ToString())
Run Code Online (Sandbox Code Playgroud)

我理解IIF函数的方式,如果e.Value是Nothing(null)那么它应该返回空字符串,否则它应该返回值的.ToString.我是,但是得到一个NullReferenceException.这对我来说没有意义.

有任何想法吗?

.net vb.net nullreferenceexception

41
推荐指数
1
解决办法
2万
查看次数