相关疑难解决方法(0)

C#List <Interface>:为什么你不能做`List <IFoo> foo = new List <Bar>();`

如果您有一个接口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)

c# generics

53
推荐指数
3
解决办法
5万
查看次数

为什么泛型类型约束会导致无隐式引用转换错误?

我创建了几个用于处理议程约会的接口和泛型类:

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)

c# generics type-constraints implicit-conversion

41
推荐指数
3
解决办法
4万
查看次数

为什么我得到"类型参数必须是无效的......"错误?

我将尝试缩短此代码示例:

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)

c# generics variant factory-pattern

7
推荐指数
2
解决办法
3418
查看次数