如何编写泛型方法的接口

时间:2015-01-08 22:55:49

标签: c# generics interface

我有类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".
}

非常感谢你的帮助:)

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

在我看来,通过将泛型类型参数推送到类/接口级别,以下内容将满足要求:

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

如果我遗漏了要求,请告诉我。

答案 2 :(得分:0)

试试这个:

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在课堂上

如果由于某种原因,您需要在界面中添加约束,则需要添加一个接口或基类,它将被放置到接口声明中,您必须在{ {1}}类,像这样:

PlayerModel