You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设备移动/固定状态打印无输出问题排查(附C#代码)

问题分析与修复方案

嘿,我一眼就瞅出问题所在啦——你的Equipment类构造函数里的赋值顺序完全搞反了!这直接导致所有设备的属性都没被正确初始化,所以后续的LINQ查询根本找不到符合条件的设备,自然就没输出咯。

1. 核心问题:构造函数赋值颠倒

原来的构造函数里写的是n = name;这类代码,这是把类的字段默认值(string类型默认是null,数值类型默认是0)赋给了方法参数,完全搞反了赋值方向!正确的做法应该是把参数的值赋给类的字段,这样才能把创建对象时传入的参数保存到类的属性里。

修正后的构造函数应该是这样:

public Equipment(string n, string d, string t, int w, int wt) {
    name = n;
    description = d;
    type = t;
    wheels = w;
    weight = wt;
}

之前的错误写法会让name、type这些字段始终保持默认值,所以当你用Mobile.type == "Mobile"查询时,所有设备的type都是null,条件根本不满足,循环自然不会执行。

2. 次要问题:拼写不一致(提前规避后续坑)

你在创建Box和Drill Machine时写的是"ImMobile",但后续如果要查询固定设备的话,拼写不统一会导致查询失败,建议统一拼写为"Immobile"(去掉中间的大写M),保持代码的一致性。

3. 修复后的完整代码

把构造函数修正,再统一拼写后,代码就能正常运行了:

using System;
using System.Collections.Generic;
using System.Linq;

public class Equipment {
    public string name;
    public string description;
    public string type;
    public int distance_moved = 0;
    public int wheels = 0;
    public int weight = 0;
    public int maintenance_cost;

    // 修正后的构造函数
    public Equipment(string n, string d, string t, int w, int wt) {
        name = n;
        description = d;
        type = t;
        wheels = w;
        weight = wt;
    }

    public void Move_By(int d) {
        distance_moved += d;
        // 用三元运算符简化代码,可读性更好
        maintenance_cost = type == "Mobile" 
            ? wheels * distance_moved 
            : weight * distance_moved;
    }
}

class Program {
    static void Main(string[] args) {
        var Equipment_list = new List<Equipment>() {
            new Equipment("Bulldozer", "Light Vehicle", "Mobile",4,0),
            new Equipment("Box", "Huge Box", "Immobile",0,10),
            new Equipment("Drill Machine", "Light Machine", "Immobile",0,20),
            new Equipment("Truck", "Heavy Vehicle", "Mobile",4,0)
        };

        // 变量名改成更清晰的eq,避免和"Mobile"关键词混淆
        var Mobile_Equipment = from eq in Equipment_list 
                               where eq.type == "Mobile" 
                               orderby eq.name 
                               select eq;

        foreach (var eq in Mobile_Equipment) {
            Console.WriteLine("{0} is a Mobile Equipment", eq.name);
        }

        Console.ReadKey();
    }
}

4. 预期运行结果

修复后运行代码,会输出:

Bulldozer is a Mobile Equipment
Truck is a Mobile Equipment

内容的提问来源于stack exchange,提问作者RenT-Boi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:37:33