Generic interface problem

与世无争的帅哥 提交于 2019-12-08 07:33:34

问题


I'd like to have one interface for all my grid related tasks.The tasks implement this interface:

public interface IDataForGrid<T>
{
    IGridResponse<T> GetList(IGridRequest request);
}

The T type is always a DTO class. I cant't create a common interface for this DTOs because they have nothing common.Just a dumb DTO with particular properties.

I'd like to use it like this :

public class Service1
{
    public IGridResponse CreateResponse(IGridRequest request)
    {

        ...
        IDataForGrid<T> aa;

        if(request == 1) aa = new CustomerGridData;
        if(request == 2) aa = new OrderGridData;

        var coll = aa.GetList();
    }
}

public class CustomerGridData : IDataForGrid<CustomerDTO>
{
   ...
}

The problem is I don't know what to put instead of the T.


回答1:


Maybe Im miss-understanding you, but couldnt you make a super class that all of your DTO's like BaseDTO

Then use it like so:

public class CustomerDTO : BaseDTO {}

IDataForGrid<BaseDTO> aa;

var coll = aa.GetList();

This way, your coll variable will be of type IGridResponse<BaseDTO> which all of your DTO object extend from.

That make sense?




回答2:


You can make the method generic as well so that T can be substituted as required:

public class Service1
{
  public IGridResponse<T> CreateResponse<T>(IGridRequest request)
  {
    ...
    IDataForGrid<T> aa;

    if(request == 1) cg = new CustomerGridData;
    if(request == 2) og = new OrderGridData;

    var coll = aa.GetList();
  }
}


来源:https://stackoverflow.com/questions/2424099/generic-interface-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!