下面的示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            IRetrievable<int, User> repo = new FakeRepository();
            Console.WriteLine(repo.Retrieve(35));
        }
    }
    class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class FakeRepository : BaseRepository<User>, ICreatable<User>, IDeletable<User>, IRetrievable<int, User>
    {
        // why do I have to implement this here, instead of letting the
        // TKey generics implementation in the baseclass handle it?
        //public User Retrieve(int input)
        //{
        //    throw new NotImplementedException();
        //}
    }
    class BaseRepository<TPoco> where TPoco : class,new()
    {
        public virtual TPoco Create()
        {
            return new TPoco();
        }
        public virtual bool Delete(TPoco item)
        {
            return true;
        }
        public virtual TPoco Retrieve<TKey>(TKey input)
        {
            return null;
        }
    }
    interface ICreatable<TPoco> { TPoco Create(); }
    interface IDeletable<TPoco> { bool Delete(TPoco item); }
    interface IRetrievable<TKey, TPoco> { TPoco Retrieve(TKey input); }
}
这个示例程序代表了我的实际程序使用的接口,并演示了我遇到的问题(在 中注释掉FakeRepository)。我希望这个方法调用一般由基类处理(在我的真实示例中,基类能够处理给它的 95% 的情况),允许通过显式指定 TKey 的类型来覆盖子类。我对 IRetrievable 使用什么参数约束似乎并不重要,我永远无法让方法调用落入基类。
此外,如果有人可以看到实现这种行为并获得我最终想要的结果的替代方法,我会非常有兴趣看到它。
想法?