Stworzyłem kilka interfejsów i klas generycznych do pracy z mianowania porządkiem obrad:Dlaczego ograniczenie typu ogólnego nie powoduje niejawnego błędu konwersji odniesienia?
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ć pewne ograniczenia na parametry typu, aby upewnić się, że tylko poprawne typy mogą zostać określone. Jednak podczas określania ograniczenia określające, że T
musi wdrożyć IAppointment<IAppointmentProperties>
, kompilator daje błąd podczas korzystania z klasy, która jest Appointment<AppointmentProperties>
:
class MyAppointment : Appointment<MyAppointmentProperties>
{
}
// This goes wrong:
class MyAppointmentEntry : AppointmentEntry<MyAppointment>
{
}
class MyAppointmentProperties : AppointmentProperties
{
public string ExtraInformation { get; set; }
}
błędu 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ś może wyjaśnić, dlaczego to nie działa?
To jest dziwne. ** ALE **: jest to rażące nadużywanie leków generycznych. Ledwo potrafię odczytać (jak mniemam) bardzo, bardzo uproszczony kod. –