标签: nullreferenceexception

正确处理lambda表达式中可能的System.NullReferenceException

这是有问题的查询

return _projectDetail.ExpenditureDetails
    .Where(detail => detail.ProgramFund == _programFund
         && detail.Expenditure.User == _creditCardHolder)
    .Sum(detail => detail.ExpenditureAmounts.FirstOrDefault(
        amount => amount.isCurrent && !amount.requiresAudit)
    .CommittedMonthlyRecord.ProjectedEac);
Run Code Online (Sandbox Code Playgroud)

表结构
ProjectDetails(1到多个)支出详细信息
支出详细信息(1到多个)支出
支出支出额(1比1)承诺月度记录

ProjectedEac是CommittedMonthlyRecords上的十进制字段.

我在单元测试中发现的问题(尽管不太可能发生),以下行可能为null:

detail.ExpenditureAmounts.FirstOrDefault(
    amount => amount.isCurrent && !amount.requiresAudit)
Run Code Online (Sandbox Code Playgroud)

我的原始查询是一个嵌套循环,在那里我将多次访问数据库,我不想重复.我在这里看到了类似的问题,但解决方案似乎并不合适.

有任何想法吗?

c# linq lambda nullreferenceexception

5
推荐指数
1
解决办法
2104
查看次数

WPF - 将字体保存到磁盘,然后实例化字体的GlyphTypeface抛出异常.为什么?

我正在讨论WPF字形和文档,并在.Net 4框架中遇到了一个空引用异常.

我将真实字体作为.ttf文件提取并保存到磁盘,然后尝试根据字体创建字形.我第一次将字体保存到磁盘并在从同一文件夹中的另一种字体创建GlyphTypeface 基于字体实例化GlyphTypeface 我得到一个空引用异常.

假设我有字体A和B. B尚未保存到磁盘(A可能已经或可能没有保存到磁盘;这似乎并不重要):

1)将B保存到与A相同的文件夹中的磁盘,
2)使用字体A
创建GlyphTypeface ,3)使用字体B =异常创建GlyphTypeface.

Null reference exception at:  
at MS.Internal.FontCache.FontFaceLayoutInfo.IntMap.TryGetValue(Int32 key, UInt16& value)  
at MS.Internal.FontCache.FontFaceLayoutInfo..ctor(Font font)  
at System.Windows.Media.GlyphTypeface.Initialize(Uri typefaceSource, StyleSimulations styleSimulations)  
at System.Windows.Media.GlyphTypeface..ctor(Uri typefaceSource)
Run Code Online (Sandbox Code Playgroud)

如果我重新启动我的应用程序并再次运行它(字体B已经在磁盘上),步骤3不会抛出异常.

将字体保存到磁盘的代码只是从二进制流中编写一个部分并放开文件:

if (!File.Exists(filename))
{
    using (FileStream fs = File.Create(filename, length))
    {
        fs.Write(m_data, m_index, length);
        fs.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我不想将每个字体都放在自己的文件夹中......

谢谢你的时间.

wpf fonts nullreferenceexception

5
推荐指数
1
解决办法
1646
查看次数

为什么我得到这个System.NullReferenceException?

我收到了一个奇怪的错误.我有以下前端代码:

<%@ Page Title="" Language="C#" MasterPageFile="~/nokernok/MasterPages/nokernok.Master" AutoEventWireup="true" CodeBehind="articleList.aspx.cs" Inherits="development.nokernok.articleList" %>
<%@ Register TagPrefix="EPiServer" Namespace="EPiServer.WebControls" Assembly="EPiServer" %>

<asp:Content ID="Content2" ContentPlaceHolderID="LeftContentPlaceHolder" runat="server">    
    <asp:Label ID="lblTest" runat="server" />    
</asp:Content>
Run Code Online (Sandbox Code Playgroud)

我有以下后端代码:

using System;
using System.Web;
using EPiServer;
using EPiServer.Core;
using development.NaafLibrary;

namespace development.nokernok
{
    public partial class articleList : TemplatePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblTest.Text = "TEEEEEEEEEEEST";    
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

设计师档案:

namespace development.nokernok {
    public partial class articleList {        
       protected global::System.Web.UI.WebControls.Label lblTest;
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个错误消息:

Object reference not set to an …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net nullreferenceexception

5
推荐指数
1
解决办法
8549
查看次数

使用没有attatched委托方法在C#中触发事件?

我刚刚在程序中遇到一个错误,我正在编写一个异常被抛出的状态,说明"对象引用必须设置为对象的实例".经过调查,我发现在尝试触发事件时抛出了此异常,但事件没有添加任何委托方法.

我想检查一下我的理解是否正确,作为开发人员,如果没有先检查事件是否等于null,就不应该触发事件?例如:

if (this.MyEventThatIWantToFire != null)
{
    this.MyEventThatIWantToFire();
}
Run Code Online (Sandbox Code Playgroud)

提前感谢您的建议/想法.

c# null events delegates nullreferenceexception

5
推荐指数
1
解决办法
2794
查看次数

如何在PresentationFramework中调试NullReferenceException?

我的.NET 4应用程序使用WPF TreeView,我已经增强了它以启用键盘导航和延迟加载.我的问题是,很少会抛出下面显示的异常.在我开发的几个月里,这只发生过一次,我收到了一些客户的错误报告,这些客户偶尔会得到这个.这是非常罕见的,我无法改变一些东西,玩一下应用程序一段时间,并知道问题是否已经消失.

但我的主要问题是:堆栈跟踪只显示Microsoft代码,那里没有任何东西.这是.NET/WPF中的错误吗?有没有机会找到根本原因?

Type: System.NullReferenceException
Message: Object reference not set to an instance of an object.
Source: PresentationFramework
Stack trace:    at System.Windows.Controls.ItemContainerGenerator.ContainerFromIndex(Int32 index)
  at System.Windows.Controls.TreeViewItem.FindNextFocusableItem(Boolean walkIntoSubtree)
  at System.Windows.Controls.TreeViewItem.InternalPredictFocus(FocusNavigationDirection direction)
  at System.Windows.Controls.VirtualizingStackPanel.FocusChanged(KeyboardFocusChangedEventArgs e)
  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
  at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
  at System.Windows.Input.InputManager.ProcessStagingArea()
  at System.Windows.Input.KeyboardDevice.ChangeFocus(DependencyObject focus, Int32 timestamp)
  at System.Windows.Input.KeyboardDevice.Focus(DependencyObject focus, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
  at System.Windows.Input.KeyboardDevice.Focus(IInputElement element)
  at System.Windows.UIElement.Focus()
  at System.Windows.Controls.TreeViewItem.OnItemsChanged(NotifyCollectionChangedEventArgs …
Run Code Online (Sandbox Code Playgroud)

.net wpf treeview exception nullreferenceexception

5
推荐指数
1
解决办法
2121
查看次数

创建线程时出现NullReferenceException

我在创建一个简单的线程池时正在看这个线程。在那里,我遇到了@MilanGardian对.NET 3.5的响应,响应非常优雅并且可以实现我的目的:

using System;
using System.Collections.Generic;
using System.Threading;

namespace SimpleThreadPool
{
    public sealed class Pool : IDisposable
    {
        public Pool(int size)
        {
            this._workers = new LinkedList<Thread>();
            for (var i = 0; i < size; ++i)
            {
                var worker = new Thread(this.Worker) { Name = string.Concat("Worker ", i) };
                worker.Start();
                this._workers.AddLast(worker);
            }
        }

        public void Dispose()
        {
            var waitForThreads = false;
            lock (this._tasks)
            {
                if (!this._disposed)
                {
                    GC.SuppressFinalize(this);

                    this._disallowAdd = true; // wait for all …
Run Code Online (Sandbox Code Playgroud)

c# debugging multithreading nullreferenceexception

5
推荐指数
1
解决办法
3008
查看次数

如何从另一个UserControl继承UserControl?

是否可以从另一个用户控件继承用户控件?

我想要实现的是从另一个用户控件继承的用户控件.所以我有baseusercontrol.ascx,这只是文本"Stuff".然后我有另一个用户控件,childusercontrol.ascx从baseusercontrol.ascx继承.如果我没有在childusercontrol.ascx中更改任何内容,我希望baseusercontrol.ascx文本显示"Stuff".

而且我应该能够扩展派生的基本用户控制功能.

我也试着像这样,但它在我的情况还不够.

现在我的childusercontrol.ascx看起来在下面

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="childusercontrol.ascx.cs" Inherits="test_childusercontrol" %>
<%@ Register src="baseusercontrol.ascx" tagname="baseusercontrol" tagprefix="uc1" %>
Run Code Online (Sandbox Code Playgroud)

childusercontrol.ascx.cs如下

public partial class test_childusercontrol : baseusercontrol
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }   
}
Run Code Online (Sandbox Code Playgroud)

当我浏览此页面时,我得到错误

Object reference not set to an instance of an object.
Description : An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. …
Run Code Online (Sandbox Code Playgroud)

asp.net inheritance user-controls nullreferenceexception

5
推荐指数
1
解决办法
7339
查看次数

关闭if大括号的NullReferenceException

我正在使用MVC和Razor视图.在这个特定的视图中,我传递的是该类的单个实例Bed.Bed有房产string Infection.现在在这个例子中,我HasInfection在视图中定义了一个布尔值,我在其他地方用它来改变显示的内容.这最初被宣布为

var HasInfection = (Model.Infection.Trim() != "";
Run Code Online (Sandbox Code Playgroud)

并按预期工作.但是,现在有一个用例Bed可能为null.这是第一个代码块:

@{
    ViewBag.Title = "Edit";
    var HasInfection = false;
    if (Model != null)
    {
        HasInfection = Model.Infection.Trim() != "";
    } // I get a NRE on this line whenever Model is null
}
Run Code Online (Sandbox Code Playgroud)

我甚至尝试过复杂的嵌套if-else解决方案,而且我仍然在结束时得到一个NRE if.

if (Model.Infection == null)
{
    HasInfection = false;
}
else
{
    if (Model.Infection != "")
    {
        HasInfection = true;
    }
    else
    {
        HasInfection = false;
    } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc nullreferenceexception razor

5
推荐指数
2
解决办法
1369
查看次数

EF - Navigation属性为null,即使在重新加载实体后也是如此,但在重新启动程序时仍然有效

编辑

我做了一些测试并发现,Item导航属性仅在处理上下文/创建新上下文时才有效.

        DataContext context = new DataContext();
        Order ord = context.Orders.FirstOrDefault();
        ord.OrderItem.Add(new OrderItem() { ItemId = 8, Quantity = 2, DateCreated = DateTime.Now });
        // At this point, both Order and Item navigation property of the OrderItem are null

        context.SaveChanges();
        // After saving the changes, the Order navigation property of the OrderItem is no longer null, but points to the order. However, the Item navigation property is still null.

        ord = context.Orders.FirstOrDefault();
        // After retrieving the order from the context …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework nullreferenceexception ef-model-first

5
推荐指数
1
解决办法
2538
查看次数

NullReferenceException在WPF中为vtk加载RenderWindowControl

我正在尝试使用ActiViz.NET和Visual Studio 2013从我的WPF项目中的vtk库加载RenderWindowControl.该库工作正常,因为我做了一个新项目只是为了练习但是当我尝试将它集成到我的工作中时,我得到了这次是一个null RenderWindowControl.这是我的代码:

MainWindow.xaml:

<Window x:Class="myProject.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:VtkTab="clr-namespace:myProject.Views.UITabs.VtkTab"
    x:Name="Mainwindow"
    MinHeight="600"
    MinWidth="800"
    Title="{Binding Title}"
    Height="720"
    Width="1280"
    Icon="{StaticResource ApplicationIcon}"
    Loaded="OnLoaded"
    DataContext="{Binding Main, Source={StaticResource ViewModelLocator}}"
    Style="{StaticResource WindowStyle}"
    mc:Ignorable="d">

    <DockPanel>
        <TabControl>
        ....
        ....
        <VtkTab:VtkTabView />
        ....
        .... 
        </TabControl>
    </DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

VtkTabView.xaml:

<UserControl x:Class="myProject.Views.UITabs.VtkTab.VtkTabView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vtk="clr-namespace:Kitware.VTK;assembly=Kitware.VTK"
        Loaded="WindowLoaded"
        Height="480" Width="640">
        <WindowsFormsHost Name="Wfh">
            <vtk:RenderWindowControl x:Name="RenderControl" />
        </WindowsFormsHost>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

VtkTabView.xaml.cs:

public partial class UITabView
{

    protected static Random _random = new Random();
    vtkActor actor = vtkActor.New();

    public VtkTabView()
    {
        InitializeComponent();

        var sphere = …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml nullreferenceexception vtk

5
推荐指数
1
解决办法
874
查看次数