如何使用 TValue 中的 IList 为 IDictionary 创建扩展方法?

How to make an extension method for a IDictionary with a IList in a TValue?

我正在努力为值中包含列表的字典定义扩展方法。

我已经这样做了:

public static bool MyExtensionMethod<TKey, TValue, K>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second) where TValue : IList<K>
    {
        //My code...
    }

要使用它,我有这个 class:

public class A
{
    public Dictionary<int, List<B>> MyPropertyA { get; set; }
}

public class B
{
    public string MyPropertyB { get; set; }
}

但是当我这样做时:

var a1 = new A();
var a2 = new A();
var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA)

我得到这个错误 'the type arguments for method '...' cannot be inferred from the usage'

如何定义或调用方法?提前致谢!!

没有泛型约束,更容易定义:

public static class Extensions
{
    public static bool MyExtensionMethod<TKey, TValue>(
        this IDictionary<TKey, List<TValue>> first,
        IDictionary<TKey, List<TValue>> second)
    {
        return true;
    }
}

public class A
{
    public Dictionary<int, List<B>> MyPropertyA { get; set; }
}
public class B
{
    public string MyPropertyB { get; set; }
}
class Program
{
    static void Main(string[] args)
    {

        var a1 = new A();
        var a2 = new A();
        var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA);
    }
}

我不确定您是否需要第三个通用参数 K。这个方法应该足够你使用了。

附带说明一下,您应该了解 Lookup class,这是一种带有键和内容列表的字典,但它是不可变的。

public static class Extensions
{
    public static bool MyExtensionMethod<TKey, TValue>(
        this ILookup<TKey, TValue> first,
        ILookup<TKey, TValue> second)
    {
        return true;
    }
}

public class A
{
    public ILookup<int, B> MyPropertyA { get; set; }
}
public class B
{
    public string MyPropertyB { get; set; }
}
class Program
{
    static void Main(string[] args)
    {

        var a1 = new A();
        var a2 = new A();
        var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA);
    }
}