纯粹的IList回归

时间:2014-09-23 14:12:52

标签: c# interface

今天我得到了一个代码,我看到了这个回归

  public IList p()
  {
      return new ListItemCollection();
  }

列表的类型在哪里?直到今天我才使用这样的方法:

public List<string> method() {}
public IList<string> method() {}
...

所以当我尝试使用 p()方法时应该怎么做:

var list = p();
check typeof(list)?

有人可以告诉我为什么只使用 IList 而不是IList类型?

2 个答案:

答案 0 :(得分:3)

IList是从.NET 1.x继承的类型,它没有泛型类型。它或多或少地被IList<T>取代,并且基本上用作IList<object>

答案 1 :(得分:2)

IListIList<T>的非通用版本,很像HashtableDictionary<T>的非通用版本。碰巧你的代码使用非泛型IList,这意味着你需要小心检查列表中存储的对象的类型,因为它们可以是任何东西。

您可以像这样检查项目的类型:

object item = yourList[0];
if(item != null && item.GetType() == typeof(string)) // replace string with another type if you like
{
    // checks that the item at index 0 isn't null and is of type String.
}