整理多个未知对象的集合

发布于 2024-11-02 06:00:40 字数 390 浏览 1 评论 0原文

我有一个场景,我有一个根类型,项目中的很多很多对象实现为一个集合,就像这样......

class Page {
  // ... 
}
interface IPages{
  IList<Page> Pages { get; set; }
}

然后有几十个对象,几乎项目中的所有内容都有 的集合页面

我需要做的是从根对象开始沿着结构树一路获取所有 Page 对象。然而,这可能非常抽象,并且很难确切地知道将会存在什么。一个简单的“foreach”循环似乎不适合它...

有没有什么方法可以从一个对象开始,检查其中的所有内容以查看它是否具有接口,如果有,则将适当的数据拉出到一个对象中主集合,递归?

I have a scenario where I have a root type that many, many, many objects in my project implement as a collection, like so...

class Page {
  // ... 
}
interface IPages{
  IList<Page> Pages { get; set; }
}

And then there are dozens of objects, almost everything in the project has a collection of Page.

What I need to do is to get all of the Page objects all the way down the structure tree from a root object. However this can be very abstract, and knowing exactly what will exist is difficult. A simple 'foreach' loop doesn't seem appropriate for it...

Is there any way to start from one object, and examine everything in it to see if it has an interface, and if so, pull the appropriate data out into a master collection, recursively?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请止步禁区 2024-11-09 06:00:40

很难说,因为 Page 似乎没有在您的示例中实现 IPages。

根据您的实现,此扩展方法可能会起作用......

public static IEnumerable<Page> GetDescendantsAndSelf(this IPages root)
{
  if(root == null)
    yield break;  // the Page doesn't implement IPages
  if(root is Page)  // the IPages is actually a Page
    yield return root as Page;
  // go through each child
  // call this method recursively and return the result
  foreach(var child in root.Pages)
    foreach(var page in child.GetDescendantsAndSelf())
      yield return page;
}

Its hard to tell, since Page doesn't appear to implement IPages in your example.

Depending on your implementation, this extension method might work...

public static IEnumerable<Page> GetDescendantsAndSelf(this IPages root)
{
  if(root == null)
    yield break;  // the Page doesn't implement IPages
  if(root is Page)  // the IPages is actually a Page
    yield return root as Page;
  // go through each child
  // call this method recursively and return the result
  foreach(var child in root.Pages)
    foreach(var page in child.GetDescendantsAndSelf())
      yield return page;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文