我有以下扩展类:
public static class MatcherExtensions
{
public static ExecMatcher<T1, T2> Match<T1, T2>(this Tuple<T1, T2> item)
{
return new ExecMatcher<T1, T2>(item.Item1, item.Item2);
}
public static ExecMatcher<T1, T2> Match<T1, T2>(this ITupleMatchable<T1, T2> item)
{
var tuple = item.PropertiesToMatch;
return new ExecMatcher<T1, T2>(tuple.Item1, tuple.Item2);
}
public static ExecMatcher<T> Match<T>(this T item) { return new ExecMatcher<T>(item); }
}
如果我创建一个元组并调用
Match()
,它将正确使用第一个扩展方法:var tuple = Tuple.Create(1, "a");
tuple.Match().With(1, "a")... // compiles just fine.
如果我创建一个 int 并调用
Match()
,它会正确地使用最后一个扩展方法。var one = 1;
one.Match().With(1)... // compiles just fine.
然而,如果我创建一个实现了
ITupleMatchable<int, string>
接口的SomeClass
类,并尝试进行匹配,编译器仍会选择第三个扩展方法,而不是第二个,尽管后者更具体:var obj = new SomeClass(1, "a");
obj.Match().With(1, "a")... // won't compile.
根据Eric Lippert类似问题的答案,我通过将第三个扩展方法放入子目录中的自己的类中来解决了这个问题,因此创建了一个更长的命名空间,使其与调用代码相比具有更多的“距离”,而不是特定于ITupleMatchable<T1,T2>
的版本。然而,这对我来说感觉像是一个hack。有没有更简洁的方法来解决这个问题?
ITupleMatchable obj = new SomeClass(1, "a");
应该可以工作,不是吗? - Alex Sikilinda