【发布时间】:2013-06-30 08:49:08
【问题描述】:
我创建了几个接口和通用类来处理日程安排:
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 必须实现IAppointment<IAppointmentProperties> 的约束时,编译器在使用Appointment<AppointmentProperties> 的类时会出错:
class MyAppointment : Appointment<MyAppointmentProperties>
{
}
// This goes wrong:
class MyAppointmentEntry : AppointmentEntry<MyAppointment>
{
}
class MyAppointmentProperties : AppointmentProperties
{
public string ExtraInformation { get; set; }
}
错误是:
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>'.
谁能解释为什么这不起作用?
【问题讨论】:
-
这很奇怪。 但是:这是对泛型的公然过度使用。我几乎看不懂(我认为是)非常非常简化的代码。
标签: c# generics implicit-conversion type-constraints