使用泛型从接口实现不同的返回类型

时间:2020-03-26 18:09:14

标签: c# asp.net-mvc oop generics interface

我有一个这样定义的接口:

public interface ISomeOrderService
{
    T GetUserNameandPass<T>();
    Task<IEnumerable<T>> FetchOrdersAsync<T>(bool useProxy, bool impersonateProxyUser);
}

对于GetUserNameandPass,我希望它在实现类中返回以下对象:

public class NameandPass
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

另一方面,对于FetchOrdersAsync,我希望它在实现类中返回以下对象:

public class SomeOrder
{
    public string prop1 { get; set; }
    public DateTime prop2 { get; set; }
    internal static async Task<IEnumerable<SomeOrder>> ConvertServiceResponseToSomeOrderListAsync(SomeResponse someResponse)
    {
        //someResult
        return someResult.ToList();
    }
}

我的实现类如下:

public class SomeOrderService : ISomeOrderService
{
    private IAMSService _aMSService;
    public SomeOrderService()
    {
        _aMSService = new AMSService();
    }
    public NameandPass GetUserNameandPass()
    {
        return _aMSService.GetProxyUser<NameandPass>("SomeTypeOfUser");
    }
    public async Task<IEnumerable<SomeOrder>> FetchOrdersAsync<SomeOrder>(bool useProxy, bool impersonateProxyUser)
    {
        //someResponse;
        return await SomeOrder.ConvertServiceResponseToSomeOrderListAsync(someResponse);
    }
}

这是我的第一个错误:

return await SomeOrder.ConvertServiceResponseToSomeOrderListAsync(someResponse);

SomeOrder is a type parameter, which is not valid in the given context.

另一个错误出现在AMSService中:

public class AMSService : IAMSService
{
    public NameandPass GetProxyUser<NameandPass>(string proxyUser)
    {
        //someProxyUserResultObject
        return new NameandPass { UserName = someProxyUserResultObject.Username, Password = someProxyUserResultObject.Password };
    }
}

这是第二个错误:

AMSService doesn't implement member 'IAMSService.GetProxyUser<T>(string)'. 'AMSService.GetProxyUser<NameandPass>(string)' cannot implement 'IAMSService.GetProxyUser<T>(string)' because it does not have matching return type of 'T'.'

IAMSService.cs看起来像这样:

public interface IAMSService
{
    T GetProxyUser<T>(string proxyUser);
}

我在这里可能做错了什么?从一开始我的接口定义不够吗?

谢谢您的帮助!

0 个答案:

没有答案