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

C# BFS路径输出问题:如何将路径节点替换为Person全名

解决C# BFS路径显示Person全名的问题

核心原因

当前输出BFS_Shortest_Path.Person是因为C#对象默认的ToString()方法会返回类型的完全限定名,而非你需要的属性组合值。

两种解决办法

方法1:重写Person类的ToString()方法(推荐)

直接在Person类里重写ToString(),让它返回Name和Address的拼接结果,这样任何地方输出Person对象时都会自动显示全名:

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }

    // 重写ToString方法,返回全名格式
    public override string ToString()
    {
        return $"{Name} {Address}";
    }
}

修改后,原有的路径输出代码无需改动,就能直接显示aa AA这类格式的全名。

方法2:输出路径时手动拼接属性

如果不想修改Person类的ToString()逻辑,可以在构建路径字符串时,遍历每个Person节点,手动获取Name和Address拼接:
假设路径是List<Person>类型的变量path,输出代码改成如下:

// 替换原直接输出Person对象的逻辑,手动拼接全名
string pathStr = string.Join(", ", path.Select(p => $"{p.Name} {p.Address}"));
// 保留步数计算,输出最终结果
Console.WriteLine($"shortest path to {targetPerson.Name} {targetPerson.Address}: {pathStr}, and destination is {path.Count - 1}");

修改后的预期输出

shortest path to aa AA: aa AA, and destination is 0
shortest path to bb BB: aa AA, bb BB, and destination is 1
shortest path to cc CC: aa AA, bb BB, cc CC, and destination is 2

内容的提问来源于stack exchange,提问作者Eden M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:57:39