C# TargetInvocationException - (should not be there?)
I am trying to make a simple app in WPF, and i've run into a bit of an anomaly. I have 2 classes: a partial class (for the WPF Window), and another public class I have set up myself. When I try to access the class I c开发者_运维技巧reated from the WPF window class, I run into a TargetInvocationException telling me the object reference is not set to an instance of an object. However, the object reference that results in the exception is set to an instance of an object.
Here's my code:
public partial class MainWindow : Window
{
CurrentParent CP = new CurrentParent();
public MainWindow()
{
InitializeComponent();
CP.Par.Add("MainCanvas");
}
}
public class CurrentParent
{
private List<string> _Par;
public List<string> Par
{
get { return _Par; }
set { _Par = value; }
}
}
Of course, this is in one namespace. I cannot see any reason why I should be getting this error, as my object reference CP clearly is an instance of CurrentParent.
Would anybody have any idea of how to fix this? Thanks in advance!
-Ian
In CurrentParent
the field _Par
is never initialized and therefore CP.Par
is null. The exception is thrown when the frameworks tries to call Add
. You need to initialze _Par
:
public class CurrentParent
{
private List<string> _Par = new List<string>();
public List<string> Par
{
get { return _Par; }
set { _Par = value; }
}
}
You are not instantiating the _Par member in the CurrentParent class. This should solve your problem:
public class CurrentParent
{
public CurrentParent()
{
this.Par = new List<String>();
}
public List<String> Par { get; set; }
}
Note that the sample uses automatic properties. Here is a more verbose sample that better highlights your problem:
public class CurrentParent
{
public CurrentParent()
{
this._Par = new List<String>();
}
public List<String> Par
{
get { return this._Par; }
set { this._Par = value; }
}
private List<String> _Par;
}
精彩评论