【问题标题】:How to convert from ICollection to IEnumerable?如何从 ICollection 转换为 IEnumerable?
【发布时间】:2014-05-21 22:52:35
【问题描述】:

在下面的代码中,return 语句正在抛出异常。

private IEnumerable<DirectoryEntry> GetDomains()
{
    ICollection<string> domains = new List<string>();

    // Querying the current Forest for the domains within.
    foreach (Domain d in Forest.GetCurrentForest().Domains)
    {
        domains.Add(d.Name);
    }

    return domains;  //doesn't work
}

有什么办法可以解决这个问题?

【问题讨论】:

  • 当方法的返回类型是 DirectoryEntry 的 IEnumerable 时,您正在尝试返回字符串集合
  • 您的示例没有意义 - 您尝试返回 IEnumerable&lt;DirectoryEntry&gt; 而是返回字符串集合...您实际尝试实现的目标缺少一些解释。

标签: c# asp.net active-directory


【解决方案1】:

将你的方法重新定义为

private IEnumerable<string> GetDomains()
{
    ...
}

因为您想要string 而不是DomainsDirectoryEntry 的列表。 (假设您要添加“d.Name”)

另外,只使用 LINQ 会容易得多:

IEnumerable<string> domains = Forest.GetCurrentForest().Domains.Select(x => x.Name);

这将返回一个IEnumerable&lt;string&gt;,并且不会浪费额外的内存来创建一个单独的列表。

【讨论】:

  • 这是不必要的,也不是问题,如果返回类型是 IEnumerable 返回字符串列表就可以了。实际问题是方法的返回类型。
【解决方案2】:

将域类型设置为IList&lt;string&gt; 或者按照 Nathan 的建议去做:

private IEnumerable<string> GetDomains()
{
  return Forest.GetCurrentForest().Domains.Select(x => x.Name);
}

【讨论】:

  • 你也可以使用 .Cast()
【解决方案3】:

为了将来参考,这也有效:

private IEnumerable<string> GetDomains()
{
  return Forest.GetCurrentForest().Domains.Cast<string>();
}

强制转换类型等于 IEnumerable 的类型。

【讨论】:

    【解决方案4】:

    ICollection&lt;T&gt; 继承自 IEnumerable&lt;T&gt;,所以你可以直接转换它:

    public interface ICollection<T> : IEnumerable<T>, IEnumerable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多