如何为泛型方法编写接口

本文关键字:接口 泛型方法 | 更新日期: 2023-09-27 18:36:54

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

这是我的班级和界面。如何使用类约束编写泛型方法实现?

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

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

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

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

试试这个:

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

在您的情况下,在实现接口的类中,您可以为类添加更多条件:

  • 界面中的where T : class
  • 课堂where T: PlayerModel

如果出于某种原因需要将约束添加到接口中,则需要添加一个接口或基类,该接口或基类将放置在接口声明中,并且必须在PlayerModel类中从中派生,如下所示:

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)
    {
        ///
    }
  }
}