纯粹的IList回归

本文关键字:回归 IList 纯粹 | 更新日期: 2023-09-27 18:24:00

今天我得到了一个要使用的代码,我看到这个返回

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

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

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

因此,当我尝试使用p()方法时,我应该做什么:

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

有人能告诉我为什么只使用IList而不使用带类型的IList吗?

纯粹的IList回归

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

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.
}