C# TargetInitationException -(不应该存在?)
我正在尝试在 WPF 中制作一个简单的应用程序,但遇到了一些异常情况。我有 2 个类:一个部分类(用于 WPF 窗口),另一个是我自己设置的公共类。当我尝试访问从 WPF 窗口类创建的类时,我遇到了 TargetInitationException ,告诉我对象引用未设置为对象的实例。但是,导致异常的对象引用被设置为对象的实例。
这是我的代码:
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; }
}
}
当然,这是在一个名称空间中。我看不出为什么会出现此错误,因为我的对象引用 CP 显然是 CurrentParent 的实例。
有人知道如何解决这个问题吗?提前致谢!
-伊恩
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 created 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
CurrentParent
中,字段_Par
从未初始化,因此CP.Par
为 null。当框架尝试调用Add
时,会引发异常。您需要初始化_Par
:In
CurrentParent
the field_Par
is never initialized and thereforeCP.Par
is null. The exception is thrown when the frameworks tries to callAdd
. You need to initialze_Par
:您没有实例化 CurrentParent 类中的 _Par 成员。这应该可以解决您的问题:
请注意,该示例使用自动属性。这是一个更详细的示例,可以更好地突出您的问题:
You are not instantiating the _Par member in the CurrentParent class. This should solve your problem:
Note that the sample uses automatic properties. Here is a more verbose sample that better highlights your problem: