简体   繁体   English

TargetInvocationException?

[英]TargetInvocationException?

Why would the following lines of code cause a TargetInvocationException exception? 为什么以下代码行会导致TargetInvocationException异常?

    private Dispatcher dispatcher = null;

    public DownloadManager(Dispatcher dispatcher = null)
    {
        this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
    }

When the DownloadManager is instantiated in the XAML like: 在XAML中实例化DownloadManager时,如下所示:

<Window.DataContext>
    <c:DownloadManager />
</Window.DataContext>

Note that the debugger doesn't specifically highlight any of these lines; 请注意,调试器没有特别突出显示这些行。 all I know is that if I delete them, my program doesn't crash. 我所知道的是,如果删除它们,则程序不会崩溃。

To instantiate an object through XAML, it needs to have a public default constructor. 要通过XAML实例化对象,它需要具有公共的默认构造函数。 A parameterized constructor with default values is not the same as a default constructor. 具有默认值的参数化构造函数与默认构造函数不同。 As such, the XAML parser is dying when trying to instantiate your object. 因此,当尝试实例化对象时,XAML分析器将崩溃。 I'd say a TargetInvocationException with a NullReferenceException as the inner is a bit worthless and something more useful could be thrown as the inner. 我会说带有NullReferenceException的TargetInvocationException作为内部对象是一文不值的,并且可能会抛出一些更有用的东西作为内部对象。

Finally, FWIW, the XAML editor in VS2010 is telling me that my Type is unusable without a default constructor when I have a constructor defined like yours. 最后,VS2010中的XAML编辑器FWIW告诉我,当我定义了与您一样的构造函数时,如果没有默认构造函数,则无法使用我的Type。

Use two constructors instead (or just a default constructor): 改用两个构造函数(或仅使用默认构造函数):

public MyViewModel()
    : this( null ) {
}

public MyViewModel( Dispatcher dispatcher = null ) {
    this._dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
}

我看不到任何东西,但是如果有一个,请查看InnerException,它表示什么?

Just a suggestion. 只是一个建议。 Can you add a default constructor to the class and see what happens? 您可以向该类添加默认构造函数,看看会发生什么吗? Like so: 像这样:

public DownloadManager()
{
   this.dispatcher = Dispatcher.CurrentDispatcher;
}

I wonder if XAML doesn't like a constructor with parameters with default values. 我想知道XAML是否不喜欢带有默认值参数的构造函数。

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

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