我用两个抽象方法创建了一个类。
在一个方法中,我按照抽象方法List中的返回类型的要求在列表中返回我的泛型类型U
在我的第二个方法中,我只是按照抽象方法中的返回类型的要求返回U,但是我得到了一个类型错误
错误CS0029:无法隐式转换类型LB.HexSphereBuild.HexTile' to
HexTile'
我不明白为什么这是隐式转换?特别是因为除了使用LB.HexSphereBuild的公共抽象类AStarFindPath之外,所有类型都在LB.HexSphereBuild命名空间之下。
请帮忙
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LB.Managers;
using LB.HexSphereBuild;
namespace LB.AStarPathFinding
{
public abstract class AStarFindPath<T,U> : MonoBehaviour{
public virtual void FindPath<T>(Vector3 startPos, Vector3 targetPos) {
}
// Method 1
public abstract U NodeFromWorldPoint<T,U> (Vector3 worldPos);
// Method 2
public abstract List<U> GetNodeNeighbours<U> (U node);
}
}
这是继承我的抽象类
的类using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LB.Managers;
using LB.AStarPathFinding;
namespace LB.HexSphereBuild
{
[RequireComponent (typeof(PlanetBuildManager))]
public class AStarHexSphere: AStarFindPath<Hexsphere,HexTile>
{
private HexSphere _hexSphereObj;
void Awake ()
{
// Reference to HexSphere
_hexSphereObj = gameObject.GetComponent<PlanetBuildManager> ().hexSphereObj;
}
override public HexTile NodeFromWorldPoint<HexSphere,HexTile> (Vector3 worldPos )
{
int startNodeIndex = _hexSphereObj.GetHexIndexFromPoint (worldPos);
int startNodeIndex = _hexSphereObj.GetHexIndexFromPoint (worldPos);
HexTile startHex = _hexSphereObj.Hexes[startNodeIndex];// error CS0029: Cannot implicitly convert type `LB.HexSphereBuild.HexTile' to `HexTile'
return startHex;
}
override public List<HexTile> GetNodeNeighbours<HexTile> (HexTile node )
{
List<HexTile> neighbours = new List<HexTile>();
List<int> hexNeighboursIndices = new List<int>();
int hexIndex =0;
_hexSphereObj.GetNeighbors (hexIndex, ref hexNeighboursIndices);
return neighbours;
}
public void FindPath (Vector3 startPos, Vector3 targetPos)
{
// Get HexTile from start and end positions
int startNodeIndex = _hexSphereObj.GetHexIndexFromPoint (startPos);
HexTile startHex = _hexSphereObj.Hexes [startNodeIndex];
int targetNodeIndex = _hexSphereObj.GetHexIndexFromPoint (targetPos);
HexTile endHex = _hexSphereObj.Hexes [targetNodeIndex];
}
}
}
添加属性,问题就在这里
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace LB.HexSphereBuild
{
[System.Serializable]
public class HexSphere
{
private List<HexTile> _hexes = new List<HexTile> ();
// Data for the hexes. Read only
public List<HexTile> Hexes {
get{ return _hexes; }
}
// ....... other stuff
}
}
添加数据类
namespace LB.HexSphereBuild
{
public class HexTile : IAStarPathFinding<HexTile>
{
// Code .....
}
}
答案 0 :(得分:2)
您已经定义了T
和U
,在您的方法中再次定义 意味着所有方法中的T
可能是不同的类型。这不是你想要的,删除方法上的泛型:
public abstract class AStarFindPath<T,U> : MonoBehaviour
{
public virtual void FindPath(Vector3 startPos, Vector3 targetPos)
{
}
// Method 1
public abstract U NodeFromWorldPoint(Vector3 worldPos);
// Method 2
public abstract List<U> GetNodeNeighbours(U node);
}