我有 PlayersCollection 类,我想在 IWorldCollection 中连接它。问题是关于在接口(interface)中编写导致我出现此错误的声明:
Assets/Scripts/Arcane/api/Collections/ItemsCollection.cs(17,22): error CS0425:
The constraints for type parameter `T' of method
`Arcane.api.ItemsCollection.Get<T>(int)
must match the constraints for type parameter `T' of
interface method `Arcane.api.IWorldCollection.Get<T>(int)'.
Consider using an explicit interface implementation instead
这是我的类和我的界面。如何编写具有类约束的泛型方法实现?
public class PlayersCollection : IWorldCollection
{
public Dictionary<Type, object> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, object>();
}
public T Get<T>(int id) where T: PlayerModel
{
var t = typeof(T);
if (!Collection.ContainsKey(t)) return null;
var dict = Collection[t] as Dictionary<int, T>;
if (!dict.ContainsKey(id)) return null;
return (T)dict[id];
}
}
}
public interface IWorldCollection
{
T Get<T>(int id) where T : class;// Work when I change "class" to "PlayerModel".
}
非常感谢您的帮助:)
在我看来,通过将泛型类型参数提升到类/接口(interface)级别,以下内容将满足要求:
public class PlayersCollection<T> : IWorldCollection<T> where T : PlayerModel
{
public Dictionary<Type, T> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, T>();
}
public T Get(int id)
{
var t = typeof(T);
if (!Collection.ContainsKey(t)) return null;
var dict = Collection[t] as Dictionary<int, T>;
if (!dict.ContainsKey(id)) return null;
return (T)dict[id];
}
}
public interface IWorldCollection<T> where T : class
{
T Get(int id);
}
如果我遗漏了要求中的某些内容,请告诉我。
我是一名优秀的程序员,十分优秀!