c# - 从 List<> 获取特定项目

标签 c# .net

我有问题!我发现很多人遇到同样的问题,但没有一个答案对我有帮助。我试图从 List<> 中获取特定项目,但我的“测试”结果返回 null,为什么?

public MainWindow()
{
    InitializeComponent();

    var modelList = new Model2();
    modelList.MyPropertyList.Add(new Model1 { Name = "Hej1", MyProperty1 = true });

    modelList.MyPropertyList.Add(new Model1 { Name = "Hej2", MyProperty1 = false });

    var test = modelList.MyPropertyList.Find(x => x.Name == "Hej1").MyProperty1;
}

最佳答案

根据OP评论

how do you know it is null? – dotctor 1 hour ago
When i debug the value is null.. – Dennis Eriksson 1 hour ago


are you sure you check the value after executing the line? try adding `MessageBox.Show(test.ToString());) and see what is the result – dotctor 1 hour ago


I feel a shame of my question.. It was working the whole time! It was my fault that i read the value before it was declared to "test"! But thanks!! – Dennis Eriksson 1 hour ago


我认为问题是您调试程序的方式。您在行 var test = modelList.MyPropertyList.Find(x => x.Name == "Hej1").MyProperty1; 上放置了一个断点,并且执行在该行之前停止 但是你认为这一行已经执行了并且 Visual Studio 在 Autos 窗口中将 test 的值显示为 null 这让你认为 test 真的是空的。如果您通过按 F10 继续执行 或添加一行 MessageBox.Show(test.ToString()); 只是为了使上一行执行或以某种方式显示 test 的值,您会发现它不是 null

关于c# - 从 List<> 获取特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830596/

相关文章:

c# - 使用字节 [] 的 Nhibernate 3.2 sqlite blob 字段通过代码映射不起作用

c# - 将 struct 与 null 进行比较时出现错误的编译器警告

c# - C# 和 VB 中的锯齿状数组 CLS 合规性不同?

.net - 数据库结构略有不同的多客户项目的架构设计(针对每个客户)

.net - 在导入/导出时具有 Markdown 功能的 GUI 控制

c# - ASP.NET MVC Beta 1 - 它是否支持强类型 View 数据?

c# - 如果 Quit() 不起作用,则终止进程

c# - System.Net.UnsafeNclNativeMethods.OSSOCK.recv 网络服务异常

c# - 单元测试中的逻辑

c# - 从 .NET Web 应用程序导出到 Outlook(.ics 文件)