2017-03-22 38 views
1

我努力为其值中包含List的字典定义扩展方法。如何在TValue中使用IList创建IDictionary的扩展方法?

我已经做到了这一点:

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

要使用它,我有这个类:

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) 

我得到这个错误'方法的类型参数'...'不能从用法'

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

回答

1

没有泛型约束,这是很容易定义:

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类,这是一种带有一个键和一个列表的字典,除了它是不可变的。

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); 
    } 
} 
+0

这工作!我会看看查找类。非常感谢。 – joacoleza

相关问题