【发布时间】:2015-07-17 08:07:14
【问题描述】:
我有一个函数可以进行加扰比较
public static int ScrambledEquals<TKey, T>(
IDictionary<TKey, T> list1,
IDictionary<TKey, T> list2)
where TKey : IComparable
where T : ICompareAsHtml or IComparable // compilation failure on this line
{
// ...
}
public static int ScrambledEquals<TKey, T>(
IDictionary<TKey, T> list1,
IDictionary<TKey, T> list2)
where TKey : IComparable
where T : ICompareAsHtml {} // This works!
TKey 必须是 IComparable,但值类型 T 可以是 IComparable 或实现下面的接口
public interface ICompareAsHtml
{
// Compare current "this" object with "obj"
// and persist the difference in html somewhere
// return number of differences.
int compareAsHtml(object obj);
}
如何更新 where 行以使编译通过(不删除它,不使用其中一个接口)?
或者更好的是,您可以阅读下面的代码以了解我的情况。我需要使用下面的函数来比较一个字符串集合,它是 IComparable;或者比较一个拥抱类的集合,比如销售,它实现了 ICompareAsHtml 但没有实现 IComparable。 (因为太多的属性使得这个类很难实现 CompareTo 功能 - 无法给出“一个”数字来表示两个实例之间的“方向”和“距离”。)
public static int ScrambledEquals<TKey, T>(
IDictionary<TKey, T> list1,
IDictionary<TKey, T> list2)
where TKey : IComparable
// where T : ICompareAsHtml or IComparable
// commented out above line to make compilation pass
{
int nDIff = 0;
List<TKey> bothKeys = list1.Keys.Union<TKey>(list2.Keys).ToList();
bothKeys.Sort();
foreach (TKey key in bothKeys)
{
// code omitted - not related to this question
{
// key exist in both lists.
object o1 = list1[key];
object o2 = list2[key];
if (o1 is IComparable && o2 is IComparable)
{
IComparable v1 = (IComparable)o1;
IComparable v2 = (IComparable)o2;
if (0 != v1.CompareTo(v2))
{
nDIff++;
// Save the difference in html
}
}
else if (o1 is ICompareAsHtml && o2 is ICompareAsHtml)
{
ICompareAsHtml v1 = (ICompareAsHtml)o1;
ICompareAsHtml v2 = (ICompareAsHtml)o2;
// Save the difference
nDIff += v1.compareAsHtml(v2);
}
else
{
// If I can use where keyword
// I don't need this exception
throw new Exception(@"Error: Program error
- Value Type is neither IComparable nor ICompareAsHtml.");
}
}
}
}
return nDIff;
}
欢迎所有建议/反馈/cmets!
【问题讨论】:
标签: c#