2012-02-24 24 views
3

我有.NET應用程序與NullReferenceException崩潰。有趣的是,該日誌顯示此:System.Object.GetType如何拋出NullRefernceException

Inner Exception System.NullReferenceException: Object reference not set to an instance of an object. 
      at System.Object.GetType() 

是令人費解的我來說,事情是例外的GetType內發生的,而不是上調用的GetType行。我測試了以下情況。

如果我對一個null對象調用GetType,異常發生在調用GetType的行上,而不在GetType內。 我也試過How can I get a NullReferenceException in this code sample?但奇怪 我在Program.Main中得到的異常不在Object.GetType中(儘管在那篇文章裏它在GetType中)。

我也試着同時創建對象並調用GetType,但針刺地說, 沒有創建.net對象的窗口,其中GetType拋出NullReferenceException。 現在我唯一想到的是這可能是一些較舊的.NET實現的行爲。

因此,任何想法如何在GetType中導致NullReferenceException,並且如果您可以提供概念代碼證明,我將永遠感激。 謝謝你的時間。

+1

你可以發佈的代碼和stacktrace或任何你可能從你的日誌? – 2012-02-24 02:53:07

回答

3

的一種方法是與call指令,而不是與C#通常使用callvirt指令調用GetType方法(「上」的null -reference)。這將阻止之前的方法調用運行時null檢查發生。相反,空引用將傳遞給該方法,從而導致該方法本身在內拋出異常

例如,使用InvokeNonVirtual樣品provided here,你可以這樣做:

var method = typeof(object).GetMethod("GetType"); 
object[] args = { null }; 

InvokeNonVirtual(method, args); 

這將產生與InnerException是一個NullReferenceException具有堆棧跟蹤一個TargetInvocationException

at System.Object.GetType() 
at NonVirtualInvoker(Object) 
+0

謝謝,我不知道這是可能的,我認爲所有的電話都需要這個!= null。很好的答案! – Ivan 2012-02-24 05:12:12

0

我知道這個帖子有點老了,但我認爲這個問題值得進一步調查。

儘管堆棧跟蹤現在沒有在System.Object.GetType()'處的附加堆棧跟蹤線'',但我設法在小型演示應用程序中複製了大部分錯誤。

我真的不知道是什麼原因造成的,但我將嫌疑人縮小到DataGrid,ComboBox.SelectedIndex屬性或標記擴展名。如果我替換這三個中的任何一個,問題就會消失,或者顯示出更加不可逾越的錯誤。

主窗口:(帶有一個可編輯列中的數據網格)

<Window  x:Class="WpfApplication2.MainWindow" 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:src="clr-namespace:WpfApplication2" 
       Title="MainWindow" 
       Height="350" 
       Width="525" 
        > 
    <DataGrid ItemsSource="{Binding Items}"> 
     <DataGrid.Columns> 
      <DataGridTemplateColumn Header="Column 1" Width="120"> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <TextBlock Text="{Binding Description}" /> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
       <DataGridTemplateColumn.CellEditingTemplate> 
        <DataTemplate> 
         <ComboBox SelectedIndex="{src:ValidatedBinding SelectedIndex}" 
            VerticalAlignment="Center" HorizontalAlignment="Center" Width="100"> 
          <ComboBoxItem>Not Specified</ComboBoxItem> 
          <ComboBoxItem>First</ComboBoxItem> 
          <ComboBoxItem>Second</ComboBoxItem> 
         </ComboBox> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellEditingTemplate> 
      </DataGridTemplateColumn> 
     </DataGrid.Columns> 
    </DataGrid> 
</Window> 

代碼驅動此窗口:

using System.Windows; 

namespace WpfApplication2 
{ 
    /// <summary> 
    /// The main window. 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 

      //DataContext = new Item { Description = "Item 1", SelectedIndex = 0 }; 

      DataContext = new DemoDataContext(); 
     } 
    } 

    /// <summary> 
    /// An object with 'Items'. 
    /// </summary> 
    public sealed class DemoDataContext 
    { 
     readonly Item[] _items = new Item[] { 
      new Item { Description = "Item 1", SelectedIndex = 0 }, 
      new Item { Description = "Item 2", SelectedIndex = 1 }, 
      new Item { Description = "Item 3", SelectedIndex = 2 }, 
     }; 

     public Item[] Items { get { return _items; } } 
    } 

    /// <summary> 
    /// An object with a string and an int property. 
    /// </summary> 
    public sealed class Item 
    { 
     int _selectedIndex; 
     string _description; 

     public string Description 
     { 
      get { return _description; } 
      set { _description = value; } 
     } 

     public int SelectedIndex 
     { 
      get { return _selectedIndex; } 
      set { _selectedIndex = value; } 
     } 
    } 
} 

標記擴展代碼:

using System; 
using System.Windows; 
using System.Windows.Data; 
using System.Windows.Markup; 

namespace WpfApplication2 
{ 
    /// <summary> 
    /// Creates a normal Binding but defaults NotifyOnValidationError and ValidatesOnExceptions to True, 
    /// Mode to TwoWay and UpdateSourceTrigger to LostFocus. 
    /// </summary> 
    [MarkupExtensionReturnType(typeof(Binding))] 
    public sealed class ValidatedBinding : MarkupExtension 
    { 
     public ValidatedBinding(string path) 
     { 
      Mode = BindingMode.TwoWay; 

      UpdateSourceTrigger = UpdateSourceTrigger.LostFocus; 

      Path = path; 
     } 

     public override object ProvideValue(IServiceProvider serviceProvider) 
     { 
      var Target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); 

      /* on combo boxes, use an immediate update and validation */ 
      DependencyProperty DP = Target.TargetProperty as DependencyProperty; 
      if (DP != null && DP.OwnerType == typeof(System.Windows.Controls.Primitives.Selector) 
       && UpdateSourceTrigger == UpdateSourceTrigger.LostFocus) { 
       UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
      } 

      return new Binding(Path) { 
       Converter = this.Converter, 
       ConverterParameter = this.ConverterParameter, 
       ElementName = this.ElementName, 
       FallbackValue = this.FallbackValue, 
       Mode = this.Mode, 
       NotifyOnValidationError = true, 
       StringFormat = this.StringFormat, 
       ValidatesOnExceptions = true, 
       UpdateSourceTrigger = this.UpdateSourceTrigger 
      }; 
     } 

     public IValueConverter Converter { get; set; } 

     public object ConverterParameter { get; set; } 

     public string ElementName { get; set; } 

     public object FallbackValue { get; set; } 

     public BindingMode Mode { get; set; } 

     [ConstructorArgument("path")] 
     public string Path { get; set; } 

     public string StringFormat { get; set; } 

     public UpdateSourceTrigger UpdateSourceTrigger { get; set; } 
    } 
} 

當我運行應用程序,我看到這個:

Main window with combobox and markup extension on selected index

如果我再次點擊第一列,取細胞進入編輯模式,我得到這個異常:

System.NullReferenceException was unhandled HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=PresentationFramework StackTrace: at System.Windows.Data.BindingExpressionBase.ConvertValue(Object value, DependencyProperty dp, Exception& e) at System.Windows.Data.BindingExpressionBase.ConvertFallbackValue(Object value, DependencyProperty dp, Object sender) at System.Windows.Data.BindingExpressionBase.get_FallbackValue() at System.Windows.Data.BindingExpressionBase.UseFallbackValue() at System.Windows.Data.BindingExpressionBase.get_Value() at System.Windows.Data.BindingExpressionBase.GetValue(DependencyObject d, DependencyProperty (trimmed)

如果我簡化了主窗口,並刪除除組合框的一切,取消註釋將創建一個有效的DataContext項目的行,然後我得到這個錯誤:

System.Windows.Markup.XamlParseException occurred
HResult=-2146233087 Message='Set property 'System.Windows.Controls.Primitives.Selector.SelectedIndex' threw an exception.' Line number '19' and line position '39'.
Source=PresentationFramework LineNumber=19 LinePosition=39
StackTrace: at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at WpfApplication2.MainWindow.InitializeComponent() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml:line 1 at WpfApplication2.MainWindow..ctor() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml.cs:line 12
InnerException: System.ArgumentException HResult=-2147024809 Message='System.Windows.Data.Binding' is not a valid value for property 'SelectedIndex'. Source=WindowsBase StackTrace: at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.Baml2006.WpfMemberInvoker.SetValue(Object instance, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value) InnerException:

相關問題