Dlaczego ogólne ograniczenie typu powoduje brak ukrytego błędu konwersji odniesienia?
Stworzyłem kilka interfejsów i klas ogólnych do pracy z terminami programu:
interface IAppointment<T> where T : IAppointmentProperties
{
T Properties { get; set; }
}
interface IAppointmentEntry<T> where T : IAppointment<IAppointmentProperties>
{
DateTime Date { get; set; }
T Appointment { get; set; }
}
interface IAppointmentProperties
{
string Description { get; set; }
}
class Appointment<T> : IAppointment<T> where T : IAppointmentProperties
{
public T Properties { get; set; }
}
class AppointmentEntry<T> : IAppointmentEntry<T> where T : IAppointment<IAppointmentProperties>
{
public DateTime Date { get; set; }
public T Appointment { get; set; }
}
class AppointmentProperties : IAppointmentProperties
{
public string Description { get; set; }
}
Próbuję użyć pewnych ograniczeń dla parametrów typu, aby zapewnić, że tylko poprawne typy mogą być określone. Jednak przy określaniu tego ograniczeniaT
musi wdrożyćIAppointment<IAppointmentProperties>
, kompilator podaje błąd podczas używania klasy, która jestAppointment<AppointmentProperties>
:
class MyAppointment : Appointment<MyAppointmentProperties>
{
}
// This goes wrong:
class MyAppointmentEntry : AppointmentEntry<MyAppointment>
{
}
class MyAppointmentProperties : AppointmentProperties
{
public string ExtraInformation { get; set; }
}
Błąd jest:
The type 'Example.MyAppointment' cannot be used as type parameter 'T' in the generic type or method 'Example.AppointmentEntry<T>'. There is no implicit reference conversion from 'Example.MyAppointment' to 'Example.IAppointment<Example.IAppointmentProperties>'.
Czy ktoś mógłby wyjaśnić, dlaczego to nie działa?