0

I'm trying to get the most specific interface that both types implement. Getting the list of interfaces is fairly easy:

var interfaces = leftType.GetInterfaces().Intersect(rightType.GetInterfaces());

Then, I traverse the list and remove interfaces that are "included" into other interfaces:

var remaining = interfaces.ToDictionary(i => i, i => true);
foreach(var iface in interfaces)
    foreach(var subIface in iface.GetInterfaces())
        remaining.Remove(subIface);

However, when trying to get the most common interface for int[] and List<int>, I get a list of three interfaces:

  • IList (non-generic)
  • IList<int>
  • IReadOnlyList<int>

First of all, why doesn't IList<T> implement non-generic IList, while IEnumerable<T> does actually implement IEnumerable?

Then, the IReadOnlyList causes a certain confusion. The name implies that the container that implements the interface prohibits modification, but the usage, on the contrary, implies that the container allows read access and doesn't care about modifications. But if so, why doesn't IList<T> implement IReadOnlyList<T>?

Maybe the whole approach is incorrect, and there's a more clever way to detect the most specific interface?

4

1 回答 1

3

IList<T>没有实现IList,因为IList<T>允许您传入对象。在这里允许使用非泛型接口会破坏类型安全。
想象一下:

IList list = new List<WhateverClass>();
list.Add(new object()); // Runtime error because the type doesn't match

IEnumerable<T>只允许你取出对象,而不是传递它们(T是协变的)。您可以遍历 an 的元素并像sIEnumerable<T>一样对待所有项目。object所以IEnumerable<T>可以IEnumerable毫无问题地实施。

List<T>此外, implements的事实IReadOnlyList<T>只是意味着List<T>履行接口所需的合同(这并没有明确禁止实际可修改)。
如果您只需要对列表的读取权限,则可以将 a 视为List<T>只读列表。

于 2013-04-03T13:26:12.273 回答