简体   繁体   English

C#TargetInvocationException-(不应该在那里吗?)

[英]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. 我试图在WPF中制作一个简单的应用程序,但遇到了一些异常情况。 I have 2 classes: a partial class (for the WPF Window), and another public class I have set up myself. 我有2个班级:部分班级(用于WPF窗口)和我自己设置的另一个公共班级。 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. 当我尝试访问从WPF窗口类创建的类时,遇到TargetInvocationException,告诉我对象引用未设置为对象的实例。 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. 我看不到出现此错误的任何原因,因为我的对象引用CP显然是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. CurrentParent领域_Par是从来没有初始化的,因此CP.Par为空。 The exception is thrown when the frameworks tries to call Add . 当框架尝试调用Add时,将引发异常。 You need to initialze _Par : 您需要初始化_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. 您没有在CurrentParent类中实例化_Par成员。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM