如何为泛型方法编写接口

How to write an interface for a generic method

我有 class PlayersCollection,我想在 IWorldCollection 中连接它。 问题是关于在接口中编写声明导致我出现此错误:

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

这是我的 class 和我的界面。如何编写具有 class 约束的泛型方法实现?

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".
}

非常感谢您的帮助:)

试试这个:

public class PlayersCollection : IWorldCollection<PlayerModel>
{

    public Dictionary<Type, object> Collection;

    public PlayersCollection()
    {
        Collection = new Dictionary<Type, object>();
    }

    public PlayerModel Get<PlayerModel>(int id)
    {
        ///
    }
  }
}


public interface IWorldCollection<T>
{
    T Get<T>(int id);
}

在您的例子中,在实现您的接口的 class 中,您为 class 添加了更多条件:

  • where T : class 界面中
  • where T: PlayerModel 在 class

如果出于某种原因,您需要在接口中添加约束,则需要添加一个接口或基础 class,这将被放置到接口声明中,您必须在你的 PlayerModel class 中从中派生出来,像这样:

public abstract class Model
{
}

public class PlayerModel : Model
{
}

public interface IWorldCollection<T> where T : Model
{
    T Get<T>(int id);
}

public class PlayersCollection : IWorldCollection<PlayerModel>
{
    ///

    public PlayerModel Get<PlayerModel>(int id)
    {
        ///
    }
  }
}

我不确定你为什么需要这个界面,但也许这会有所帮助:

public class PlayersCollection<T> : IWorldCollection<T> where T:PlayerModel
{

public Dictionary<Type, object> Collection;

public PlayersCollection()
{
    Collection = new Dictionary<Type, object>();
}

public T Get(int id)
{
    ...
}
}



public interface IWorldCollection<T> where T:class
{
    T Get(int id);
}

在我看来,通过将泛型类型参数提升到 class/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);
}

如果我在要求中遗漏了什么,请告诉我。