简体   繁体   中英

Generics - return different type object

I have a bunch of methods defined on my interface that look like this:

T Map<T>( SomeType someParam ); 

and are implemented like this:

public T Map<T>( SomeType someParam )
{
  return AutoMapper.Mapper.Map<SomeType, T>( someParam );
}

How can I simplify my interface so that I just have one method like:

T Map<T>(T someParam);

and

public T Map<T>( T someParam )
{
  return AutoMapper.Mapper.Map<T, T>( someParam );
}

However, when I implement it this way, I get a conversion error about converting from SomeType and another type. Is this possible to do with generics, how?

Just provide more generic type parameter:

public T1 Map<T1,T2>( T2 someParam){
  return AutoMapper.Mapper.Map<T1, T2>( someParam);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM