无法将类型从System.Collection.Generic.IEnumerable.MyClass <node>隐式转换为MyClass <node>

时间:2015-06-10 07:19:28

标签: c# generics neo4j neo4jclient

以下是生成错误的代码:

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> >;

现在它给出的新错误是:

  

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

我哪里错了?

1 个答案:

答案 0 :(得分:2)

你有几个可能性:

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

    var res = pathsQuery.Results.FirstOrDefault();
    
  3. 通常最好设置一个断点并将鼠标放在var上以检查它是什么类型。在这种情况下更好地避免var并使编译器报告所有问题。