Tôi đã tạo ra một vài giao diện và các lớp học chung để làm việc với các cuộc hẹn chương trình nghị sự:Tại sao kết quả ràng buộc kiểu chung loại không có lỗi chuyển đổi tham chiếu ngầm định?
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; }
}
Tôi đang cố gắng sử dụng một số những hạn chế trên các thông số loại để đảm bảo rằng chỉ các loại hợp lệ có thể được xác định. Tuy nhiên, khi xác định một hạn định rằng T
phải thực hiện IAppointment<IAppointmentProperties>
, trình biên dịch đưa ra một lỗi khi sử dụng một lớp học đó là Appointment<AppointmentProperties>
:
class MyAppointment : Appointment<MyAppointmentProperties>
{
}
// This goes wrong:
class MyAppointmentEntry : AppointmentEntry<MyAppointment>
{
}
class MyAppointmentProperties : AppointmentProperties
{
public string ExtraInformation { get; set; }
}
Lỗi này là:
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>'.
Ai có thể giải thích tại sao điều này không hoạt động?
Điều này thật kỳ quặc. ** NHƯNG **: đây là một cách sử dụng quá mức của thuốc generic. Tôi chỉ có thể đọc những gì (tôi cho là) rất, rất đơn giản mã. –