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

标签 c# generics interface

我有 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/

相关文章:

c# - 如何为 ASP.NET 5 应用程序设置语言环境?

objective-c - block 中的 Objective C 泛型

java - 具有泛型方法参数、返回类型和接口(interface)的工厂

c# - 为什么嵌套公共(public)类比它的父类更难访问?

c# - 使用 StructureMap 连接不同的实现

java - 扩展/实现这些接口(interface)需要泛型吗?

java - 为什么我们在实现 Interface 方法时使用 @Override ?它真的重写了方法吗?

c# - Python 是否适合编写标准、兼容且完整的 SOAP Web 服务?

c# - 我可以将某些东西注入(inject)到 MvcApplication 中吗?

未检测到 C# 方法(Yield)返回路径