C# Int32.TryParse引发NullReferenceException

C# Int32.TryParse引发NullReferenceException,c#,visual-studio-2010,silverlight,nullreferenceexception,silverlight-5.0,C#,Visual Studio 2010,Silverlight,Nullreferenceexception,Silverlight 5.0,注:本公司对此不承担任何责任 我现在遇到了一个奇怪的错误。我对Int32.TryParsestring,out int的调用给了我一个System.NullReferenceException 想法非常简单-用技术表示替换元数据条目,而不是使用整数值: public void GenerateClipName() { // Copy metadata entries, to prevent modifications on the actual viewmodel var met

注:本公司对此不承担任何责任

我现在遇到了一个奇怪的错误。我对Int32.TryParsestring,out int的调用给了我一个System.NullReferenceException

想法非常简单-用技术表示替换元数据条目,而不是使用整数值:

public void GenerateClipName()
{
    // Copy metadata entries, to prevent modifications on the actual viewmodel
    var metadataEntries = ViewModel.MasterObject.MetadataEntries.Copy();
    // Get the correct entry
    var entry = metadataEntries.Single(m => m.Key.EndsWith("/" + MetaDataKeys.TITLE));
    // Get all valid entries for the metadata key
    var validEntries = MetadataDefinitions.Single(x => x.Id.EndsWith("/" + MetaDataKeys.TITLE));
    int parsedInt;
    // Try to parse the integer value, and replace it with the technical representation
    if (int.TryParse(entry.Value, out parsedInt))
        entry.Value = validEntries.ValidEntries.Single(m => m.Value == parsedInt).TechnicalRepresentation;

    // Some further actions will be implemented here later
}
但预期输出更像是意外输出:

正如您在编辑器窗口下方的“局部变量”窗口中所看到的:entry.value的值为86

编辑1: 根据请求,执行Int32.TryParse之前的变量:

编辑2: 异常堆栈跟踪:

at ...Presenter.GenerateClipName()
at ...Presenter.Cancel()
at ...View.CancelButton_Click(object sender, System.Windows.RoutedEventArgs e)

堆栈跟踪不包括Int32.TryParse方法,这让我感到奇怪。

我怀疑null引用与字符串无关,而是与out变量有关:请注意,在屏幕截图底部,parsedInt为null。就我个人而言,我不喜欢可为null的整数,但如果在创建int parsedInt=0时将其初始化为0;它应该可以解决您的问题。

out参数修饰符不能返回空值,我在调试窗口中看到的情况似乎就是这样。试着给它一个值


虽然作为参数传递的变量不必 在传递之前已初始化,被调用的方法需要 在方法返回之前指定一个值

关于输出参数:

关于您的代码,您正在使用int.TryParsestring,out int,尝试将其更改为Int32.TryParsestring,out int,看看这是否解决了问题。

最终解决了: 在发布模式下运行的调试资源与编译的发布资源相同。 然而,由于拖动黄色的调试光标在代码中跳跃,VisualStudio在特定的行中弄乱了信息。
因此,引发了NullReferenceException。

我认为sendungsTitel为null。有可能VS指向错误的行,并且该异常实际上是从其他地方引发的。尝试清理和重建解决方案。另外,请检查堆栈跟踪。@DavidArno抱歉。由于公司限制发布源代码而导致的复制粘贴错误:已修复。是否已在发布模式或调试模式下生成?您可以发布异常的堆栈跟踪吗?@codroipo发布模式。对于int、byte、structs等值类型,情况并非如此。只有当声明为null的int?,byte?,structs?没有TryParsing方法时,它们才为null。我知道,我的错,只有在我注意到我的错误之后。Editedint只是Int32的别名,因此int.TryParse和Int32.TryParse.TIL之间没有区别。不知道作为输出参数传递的变量在传递之前不必初始化