Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

get different result from extension method

Open lizhanglong opened this issue 5 months ago • 3 comments

first: public static TDest MapAdapt<TDest>(this object source, TDest dest) { return source.Adapt(dest); }

second: public static TDest MapAdapt<TSource, TDest>(this TSource source, TDest dest) { return source.Adapt(dest); }

first method get result like:source.Adapt<TDest>(); second method works well.

Bug?

lizhanglong avatar Jul 30 '25 09:07 lizhanglong

@lizhanglong What version of Mapster are you using? Try the latest prerelease.

DocSvartz avatar Jul 30 '25 10:07 DocSvartz

I tested this with versions 7.3 and 7.4, and the issue persisted. It worked fine with version 7.4.2-pre02. However, versions 7.4 and above do not support the .NET Framework.

lizhanglong avatar Jul 31 '25 01:07 lizhanglong

This is related to the definition of the Type of the generic parameter. Mapster does not have a signature such Adapt<TDest>(this object source, TDest dest), there is only Adapt<TSource,TDestination>.

For your first case, a conversion from Adapt<object, TDestination> is obtained. Which actually does not make sense in the Object type there is no internal state that could be transferred to the TDestination type :)

If the source type can really be found out only at runtime, then in your case you should use the following adapter Adapt(this object source, object destination, Type sourceType, Type destinationType).

public static TDest MapAdapt<TDest>(this object source, TDest dest)
{
    if (source is null || source.GetType() == typeof(object))
        return dest; // infinite loop if source is real instance of Object var source = new Object()

    return (TDest)source.Adapt(dest, source.GetType(), typeof (TDest));
}

DocSvartz avatar Jul 31 '25 04:07 DocSvartz