c# - C# 中的嵌套泛型问题

标签 c# generics

我有这些定义:

public interface IHasId
{
    string Id { get; set; }
}


public class Something : IHasId
{
    public string Id { get; set; }
}


public class Queueable<T>
    where T : IHasId, new()
{
    public T Item { get; set; }
    public int QueueId { get; set; }
}


public class Queue<T>       
    where T : Queueable<T>, IHasId, new()
{
    public void Enqueue(T item)
    {

    }

    public T Dequeue()
    {
        return default(T);
    }
}


public class QueueService
{
    private Queue<Queueable<Something>> queue;
    //private Queue<Queueable<SomethingElse>> somethingElseQueue;
}

当我编译这个时,我得到了这些错误:

**Error**: The type 'test.Queueable<test.Something>' cannot be used as type parameter 'T' in the generic type or method 'test.Queue<T>'. There is no implicit reference conversion from 'test.Queueable<test.Something>' to 'test.IHasId'.

**Error**: The type 'test.Queueable<test.Something>' cannot be used as type parameter 'T' in the generic type or method 'test.Queue<T>'. There is no implicit reference conversion from 'test.Queueable<test.Something>' to 'test.Queueable<test.Queueable<test.Something>>'.

这是约束的问题吗? 我正在考虑为 Queue 类使用 2 种类型,一种用于实现 IHasId,另一种用于 Queueable,但我希望这实际上更容易解决。

想法?

提前致谢!

最佳答案

如果我正确地解释了你的意图,你想要这个:

public class Queue<T>       
    where T : IHasId, new()
{
    public void Enqueue(Queueable<T> item)
    {
    }

    public Queueable<T> Dequeue()
    {
        return default(Queueable<T>);
    }
}

或者:

public class Queue<TItem, TQueueable>   
    where TItem : IHasId, new()
    where TQueueable: Queueable<TItem>
{
    public void Enqueue(TQueueable<TItem> item)
    {
    }

    public TQueueable<TItem> Dequeue()
    {
        return default(TQueueable<TItem>);
    }
}

最后一种是post flexible form possible。

关于c# - C# 中的嵌套泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235950/

相关文章:

c# - Log4net EventLogAppender 只能在根记录器中工作,为什么?

c# - 如何在 LINQ 中加入未知数量的列表

generics - Swift 泛型和下标 - 值与 K 不同

java - 循环中的泛型,试图避免强制转换

c# - 为什么我的Gridview点击第2页后会消失(Paging)

javascript - 如何在 Windows 8.1 触摸屏中处理 mouseover 和 mouseleave 事件

C#反射: How to set nested Property of nested Lists

java - 什么是原始类型,为什么我们不应该使用它?

C# 打印 for 循环

c# - 泛型的观察者模式