无法将类型从 System.Collection.Generic.IEnumerable.MyClass

本文关键字:MyClass IEnumerable Node Generic Collection 类型 System | 更新日期: 2023-09-27 17:55:11

以下是

为其生成错误的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Neo4jClient;
using Neo4jClient.Cypher;
namespace ConsoleApplication1
{   
    public class SNode
    {
        public int shelfid { get; set; }
        public int floorid { get; set; }
    }
    public class PathsResult<TNode>
    {
        public IEnumerable<Node<TNode>> Nodes { get; set; }
        public IEnumerable<RelationshipInstance<object>> Relationships { get; set; }
    }
    class Program
    {
        public static PathsResult<SNode> getPath(int sourceShelfId, int destinationShelfId, GraphClient client)
        {
            var pathsQuery =
            client.Cypher
                .Match("p = shortestPath((src:Node)-[*..150]-(dest:Point))")
                .Where((SNode src) => src.shelfid == sourceShelfId)
                .AndWhere((SNode dest) => dest.shelfid == destinationShelfId)
                .Return(p => new PathsResult<SNode>
                {
                    Nodes = Return.As<IEnumerable<Node<SNode>>>("nodes(p)"),
                    Relationships = Return.As<IEnumerable<RelationshipInstance<object>>>("rels(p)")
                });
            var res = pathsQuery.Results;
            return res;
        }
    }
}

我收到的错误是:

Cannot implicitly convert type System.Collection.Generic.IEnumerable<ConsoleApplication1.PathResult<ConsoleApplication1.SNode> > 
to ConsoleApplication1.PathResult<ConsoleApplication1.SNode> >. An explicit conversion exists, are you missing a cast?

据我所知,pathQuery.result应该返回一个PathResult对象。但是,我尝试根据上述错误进行转换,如下所示:

var res = pathsQuery.Results.AsEnumerable<PathsResult<SNode> >;

现在它给出的新错误是:

无法将方法组分配给隐式类型的局部变量

我哪里出错了?

无法将类型从 System.Collection.Generic.IEnumerable.MyClass<Node> 隐

您有几种可能性:

  1. getPath的返回类型更改为IEnumerable...
  2. 仅使用查询结果的第一个元素:添加.FirstOrDefault()

    var res = pathsQuery.Results.FirstOrDefault();
    

通常,最好设置断点并将鼠标放在var上以检查它是什么类型。在这种情况下避免var甚至更好,并使编译器报告所有问题。