Skip to main content
 首页 » 编程设计

c#之从 List> 获取特定项目

2024年02月06日13qq78292959

我有问题!我发现很多人遇到同样的问题,但没有一个答案对我有帮助。我试图从 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。