[SOLVED] How to create a map for generic types with Mapster?

Issue

This Content is from Stack Overflow. Question asked by Michele Benolli

I need to configure a custom mapping between two generic classes using Mapster.

public class Source<T>
{
    public T Value { get; set; }
}

public class Destination<T>
{
    public T Value { get; set; }
}

I made the following attempts but the syntax is not correct:

TypeAdapterConfig<Source<>, Destination<>>.NewConfig()
    .Map(dest => dest.Value, src => src.Value);

TypeAdapterConfig<Source<T>, Destination<T>>.NewConfig()
    .Map(dest => dest.Value, src => src.Value);

I searched for an answer and read the Mapster documentation, but couldn’t find a solution. Is this a limitation of the mapping library? Is there any way to do this kind of mapping?



Solution

You cannot have a generic type with generic type parameters unless you’re in an appropriate generic context. So you cannot just create a mapping for all source/target combinations like this.

You can make things slightly nicer to write via a helper function, like

public void MapSourceToDestination<T>() {
  TypeAdapterConfig<Source<T>, Destination<T>>.NewConfig()
    .Map(dest => dest.Value, src => src.Value);
}

But you would still need to call that for every T to support.


This Question was asked in StackOverflow by Michele Benolli and Answered by Zastai It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?