简体   繁体   中英

Can I avoid the typecasting of interface method parameters to concrete types for same family of classes?

I have 3 interfaces roughly as follows : IData which wraps around required data IDataInfo to provide meta-data about the IData and

IDataProvider
{
   IData GetData(IDataInfo iDataInfo);
}

I have several family of derived interfaces for the above interfaces. For Eg :

  1. IBikeData : IData , IBikeDataInfo : IDataInfo and IBikeDataProvider : IDataProvider
  2. ICarData : IData , ICarDataInfo : IDataInfo and ICarDataProvider : IDataProvider and so on.

Now, in the concrete implementations of IData GetData(IDataInfo iDataInfo) for IBikeDataProvider and ICarDataProvider I need to typecast the incoming iDataInfo parameter to respective derived types ( IBikeDataInfo and ICarDataInfo ) for other to access other specific functionalities. I am slightly uncomfortable with this typecasting in each concrete implementation, which I think is not right thing to do. Is there a way I can refactor my design to prevent this ?

Seems like generics would be the answer here, assuming you can adjust your IDataProvider interface. If you make a contravariant and covariant type parameter to coincide with your IData and IDataInfo types, you can switch the definition up to get something like this:

public interface IDataProvider<in TIn, out TOut> where TIn : IDataInfo 
                                                 where TOut : IData 
{
    TOut GetData(TIn dataInfo);
}

Your IBikeDataProvider interface could then be declared as the following:

public interface IBikeDataProvider : IDataProvider<IBikeDataInfo, IBikeData> { }

Which would lead to the following concrete class instance:

public class BikeDataProvider : IBikeDataProvider
{
    public IBikeData GetData(IBikeDataInfo dataInfo)
    {
        // Do things
    }
}

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