샘플 프로그램은 :제네릭 동작을 설명하고 해결 방법이 있습니까? 아래
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에 어떤 매개 변수 제약 조건을 사용하는지는 중요하지 않지만 기본 클래스로 전달되는 메서드 호출은 결코 얻을 수 없습니다.
또한 이런 종류의 동작을 구현하고 궁극적으로 내가 원하는 결과를 얻는 다른 방법을 볼 수 있다면 매우 흥미로울 것입니다.
생각하십니까?
불행히도 원래의 예제에 포함시키지 않았지만, FakeRepository에는 여러 개의 IRetrievable 인터페이스가 정의되어있을 수 있습니다. 모든 인터페이스는 동일한 TPoco이지만 다른 TKey가 있습니다. –