我有一个问题,我的自定义IComparer没有被调用。我想也许它可能与我有关,期望它能与不同的对象一起工作?为什么没有被召唤?
Icomparer:
public class MyComparer : IComparer<object>
{
public string[] needles { get; set; }
public MyComparer(string[] argument)
{
needles = argument;
}
public int Compare(object x, object y)
{
int rankA = x.getRankedResults(needles);
int rankB = y.getRankedResults(needles);
if (rankA > rankB) { return 1; }
else if (rankA < rankB) { return -1; }
else { return 0; }
}
}
public static class MyComparerExtensions
{
public static int getRankedResults(this object o, string[] needle)
{
int result = 0;
if (o.GetType() == typeof(StaticPage))
{
var orig = o as StaticPage;
result = needle.countOccurences(orig.PageTitle.StripHTML(), orig.BodyCopy.StripHTML());
}
else if (o.GetType() == typeof(CustomerNewsArticle))
{
var orig = o as CustomerNewsArticle;
result = needle.countOccurences(orig.Title.StripHTML(), orig.BodyCopy.StripHTML());
}
else if (o.GetType() == typeof(Blog))
{
var orig = o as Blog;
result = needle.countOccurences(orig.Title.StripHTML(), orig.Body.StripHTML());
}
else if (o.GetType() == typeof(PressRelease))
{
var orig = o as PressRelease;
result = needle.countOccurences(orig.title.StripHTML(), orig.body.StripHTML());
}
return result;
}
//count the total occurences of the needles inside the haystack
private static int countOccurences(this string[] needle, params string[] haystack)
{
int occurences = 0;
foreach (var n in needle)
{
foreach (var h in haystack)
{
var nh = h;
int lenghtDif = nh.Length - nh.Replace(n, "").Length;
occurences = occurences + (lenghtDif / n.Length);
}
}
return occurences;
}
}
以及如何调用它:
string[] needles = new string[] { "one", "two", "three" };
Haystacks.OrderBy(o=> o, new MyComparer(needles));
所以&#34;干草堆&#34;有42个不同类型的对象(它们是来自不同表的行,内部&#34; getRankedResults&#34;我检测对象的类型并选择用于计算等级值的字段)。当我在排序上调用MyComparer时,我可以看到在构造函数中设置的参数,然后&#34;比较(对象x,对象y)&#34;永远不会被召唤。