C# 如何从ICollection转换为IEnumerable?
在下面的代码中,return语句引发异常C# 如何从ICollection转换为IEnumerable?,c#,asp.net,active-directory,C#,Asp.net,Active Directory,在下面的代码中,return语句引发异常 private IEnumerable<DirectoryEntry> GetDomains() { ICollection<string> domains = new List<string>(); // Querying the current Forest for the domains within. foreach (Domain d in Forest.GetCurrentFore
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
}
private IEnumerable GetDomains()
{
ICollection域=新列表();
//正在查询当前林中的域。
foreach(Forest.GetCurrentForest().Domains中的域d)
{
域。添加(d.Name);
}
返回域;//不工作
}
此问题的可能解决方案是什么?将域类型设置为
IList
或者按照内森的建议去做:
private IEnumerable<string> GetDomains()
{
return Forest.GetCurrentForest().Domains.Select(x => x.Name);
}
private IEnumerable GetDomains()
{
返回Forest.GetCurrentForest().Domains.Select(x=>x.Name);
}
将您的方法重新定义为
private IEnumerable<string> GetDomains()
{
...
}
这将返回一个IEnumerable
,并且不会浪费额外的内存创建一个单独的列表。ICollection
继承自IEnumerable
,因此您可能只需强制转换它:
public interface ICollection<T> : IEnumerable<T>, IEnumerable
公共接口ICollection:IEnumerable,IEnumerable
当方法的返回类型是DirectoryEntry的IEnumerable时,您尝试返回字符串集合。您的示例毫无意义-您尝试返回IEnumerable
,但返回字符串集合。。。对于您实际试图实现的目标,缺少一些解释。这是不必要的,也不是问题,如果返回类型为IEnumerable,则返回字符串列表就可以了。实际的问题是该方法的返回类型
public interface ICollection<T> : IEnumerable<T>, IEnumerable