I have seen examples to write class extensions for generics a couple of di开发者_StackOverflow社区fferent ways. I am going to use AutoMapper as an example.
1)
public static class Extensions<Src, Tgt>
{
public static Tgt TransferData(this Src source)
{
AutoMapper.Mapper.CreateMap<Src, Tgt>();
return AutoMapper.Mapper.Map<Src, Tgt>(source);
}
}
2)
public static class Extensions2
{
public static Tgt TransferData<Src, Tgt>(this Src source)
{
AutoMapper.Mapper.CreateMap<Src, Tgt>();
return AutoMapper.Mapper.Map<Src, Tgt>(source);
}
}
Which is better? Why? Is the first one even correct?
No, the first one isn't correct. Extension methods have to be defined in a top-level, static non-generic class.
Additionally, I'd suggest complying with the naming conventions for type parameters, too:
public static class Extensions2
{
public static TTarget TransferData<TSource, TTarget>(this TSource source)
{
AutoMapper.Mapper.CreateMap<TSource, TTarget>();
return AutoMapper.Mapper.Map<TSource, TTarget>(source);
}
}
精彩评论