gpt4 book ai didi

c# - 如何为泛型方法编写接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:46 24 4
gpt4 key购买 nike

我有 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);
}

如果我遗漏了要求中的某些内容,请告诉我。

关于c# - 如何为泛型方法编写接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com