开发者

What is the correct way to write extensions generically?

开发者 https://www.devze.com 2023-03-22 03:45 出处:网络
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.

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);
    }
}
0

精彩评论

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