簡體   English   中英

使用元組作為接口泛型的顯式接口實現不起作用

[英]Explicit interface implementation with tuple as interface generic not working

情況
我正在嘗試實現一個專門的集合,為項目分配權重。
我不能使用List<(T, double)>因為集合需要跟蹤更多信息以提供特殊功能。
但是,這個集合應該實現IList<(T, double)> ,以便我可以使用一些擴展方法。

方法

實現接口工作:

public class WeightedList<T> : IList<(T item, double weight)> 
{
    public void Add((T item, double weight) item)
    {
        this.Add(item.item, item.weight);
    }

    [...]
}

但是,為了保持實現干凈,我想顯式地實現它的一些方法。

public class WeightedList<T> : IList<(T item, double weight)> 
{
    // The method name Add is marked as source of error
    void IList<(T item, double weight)>.Add((T item, double weight) item)
    {
        this.Add(item.item, item.weight);
    }

    [...]
}

問題
但是現在,我突然收到錯誤,似乎不再識別顯式接口實現。

錯誤 CS0535:“WeightedList”未實現接口成員“ICollection<(T item, double weight)>.Add((T item, double weight))”

錯誤 CS0539:在可實現的接口成員中未找到顯式接口聲明中的“WeightedList.Add((T item, double weight))”

我所做的唯一更改是將方法更改為顯式實現。
到目前為止,這對我來說非常有用,但是使用元組作為接口泛型似乎會破壞它。
我還為接口嘗試了未命名的元組(例如IList<(T, double)> ),但這並沒有改變任何東西。

問題
為什么我會收到這些錯誤,我該如何解決?

在顯式接口實現中,state 正確的接口很重要:

public class WeightedList<T> : IList<(T item, double weight)> 
{
    // The method name Add is marked as source of error
    void ICollection<(T item, double weight)>.Add((T item, double weight) item)
    {
        this.Add(item.item, item.weight);
    }

    [...]
}

IList<T>派生自ICollection<T> Add方法是在基接口而不是派生接口中聲明的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM