C#泛型类继承

时间:2015-12-01 18:40:41

标签: c# inheritance

我有一个基类BaseRepository,其他类扩展。

public class BaseRepository
{
    protected RestClient client;
    protected string url;

    public BaseRepository ()
    {
        client = RestClient.GetInstance ();
    }

    public async Task<T> Find<T> (string id) {
        dynamic response = await client.Find(url, id);

        return DeserializeItem<T> (response);
    }
}

然后我有一个从基类扩展的UsersRepository类。

public class UsersRepository : BaseRepository
{
    string url = "users";
    static UsersRepository instance;

    private UsersRepository ()
    {
    }

    public static UsersRepository GetInstance() {
        if (instance == null) {
            instance = new UsersRepository ();
        }

        return instance;
    }
}

我无法弄清楚如何将User作为public async Task<T> Find<T> (string id)方法的响应类型。我可以在UsersRepository中创建此方法,但我不想复制代码。

public override function User Find(string id) {
    return base.Find<User>(id);
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

看起来你真的想要在基类上定义的泛型类型而不是方法。另外我想你想在派生类的构造函数中设置基类中定义的url

public class BaseRepository<T>
{
    protected RestClient client;
    protected string url;

    public BaseRepository ()
    {
        client = RestClient.GetInstance ();
    }

    public async Task<T> Find(string id) {
        dynamic response = await client.Find(url, id);

        return DeserializeItem<T> (response);
    }
}

public class UsersRepository : BaseRepository<User>
{
    static UsersRepository instance;

    private UsersRepository ()
    {
        url = "users";
    }

    public static UsersRepository GetInstance() {
        if (instance == null) {
            instance = new UsersRepository ();
        }

        return instance;
    }
}