简体   繁体   中英

Generic interface in C#

I have a generic interface and I want to constrain types that this generic parameter can accept. Here is the interface:

public interface IBaseRequestRepository<T> where T : IRequestPackage,
       IRequestDynamicPackage, IRequestHotelOnly, IRequestFlightOnly 
{ 
        IList GetByOccupancyAndTravelDate(int occupancyId, int travelBegYear,
                                          int travelBegDate, int travelEndYear,
                                          int travelEndDate); 
}

But this gives an error:

Error 1 The type 'IRequestPackage' cannot be used as type parameter 'T' in the generic type or method 'IBaseRequestRepository'. There is no implicit reference conversion from 'IRequestPackage' to 'IRequestFlightOnly'.

Any suggestions?

You need to satisfy all generic constraints and not just one.

Thus you can't substitute IRequestPackage into T because it doesn't derive from all the other interfaces.

You can pass in either an interface type that inherits from all the interfaces you specified as a constraint or a class type that implements all these interfaces.

The error message suggests that IRequestPackage does not inherit from IRequestFlightOnly - does it?

Note that the where clause is an AND relationship, not an OR - so your where clause is that T must implement ALL of

  • IRequestPackage,
  • IRequestDynamicPackage
  • IRequestHotelOnly,
  • and IRequestFlightOnly

看起来你想要一个IRequest接口或RequestBase抽象类;)

You should use a type that implement all the interfaces specified by the constraint, not just one of them. It's an "AND", not an "OR"...

You should reconsider your type constraints and your program structure. It looks like you are missing a base interface or an abstract base class.

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