如果您有一个接口IFoo和一个类Bar : IFoo,为什么可以执行以下操作:
List<IFoo> foo = new List<IFoo>();
foo.Add(new Bar());
Run Code Online (Sandbox Code Playgroud)
但你做不到:
List<IFoo> foo = new List<Bar>();
Run Code Online (Sandbox Code Playgroud) 我创建了几个用于处理议程约会的接口和泛型类:
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 …Run Code Online (Sandbox Code Playgroud) 我将尝试缩短此代码示例:
public interface IThing
{
//... Stuff
}
public class Thing1 : IThing
{
}
public class Thing2 : IThing
{
}
public interface IThingView<out T>
{
ICollection<T> ViewAll();
}
public class ThingView<T> : IThingView<T>
{
ICollection<T> ViewAll() { return new List<T>(); } // There's a big operation here
}
public interface IThingViewerFactory
{
public IThingView<IThing> Build(string Which);
}
public class ThingViewerFactory
{
public IThingView<IThing> Build(string Which)
{
if(Which.Equals("Thing1") { return new (IThingView<IThing>)new ThingViewer<Thing1>();}
else { return new (IThingView<IThing>)new ThingViewer<Thing2>();} …Run Code Online (Sandbox Code Playgroud)