开发者

Using Concrete class as type parameter for inherited generic base class

开发者 https://www.devze.com 2023-04-11 11:10 出处:网络
I have a base class with the following signature public class ReportVie开发者_开发技巧wModelBaseDTO<VT,DT>

I have a base class with the following signature

public class ReportVie开发者_开发技巧wModelBaseDTO<VT,DT>

and concrete classes like these

public class ChartViewModelDTO:ReportViewModelBaseDTO<ChartViewModel,ChartViewModelDTO>

My question is, I know that the second type parameter of my generic base class should be the type of the concrete class. I don't want to repeat myself all the time by naming the class and then repeating that name as the type parameter.

Is there any way to have my generic base class take the actual concrete class as a type paramaeter? does anyone have any suggestions on better ways to do this?

EDIT:

an example of how I want to use DT is below. I create an instance of type DT from one of type VT thru Automapper.

public static DT Create(VT viewModel)
        {
            return Mapper.Map<VT,DT>(viewModel);   
        }


Is this what you mean?

public class ReportViewModelBaseDTO<VT,DT> where DT : ReportViewModelBaseDTO<VT,DT>

Now your class 'knows' that the second type parameter is a concrete implementation of itself.

For your example method could you do:

public static DT Create(VT viewModel)
{
  return Mapper.Map<VT, DT>(viewModel);   
}

and define Mapper.Map as:

private U Map<T, U>(ViewModel viewModel) where U : ReportViewModelBaseDTO<T,U>{...}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号