[英]How can I group properties of different types in C#?
In class DiamondListingPage : PageBase I try to create one grouped enumerated property, which contains other objects with different types derived also from PageBase. 在类DiamondListingPage:PageBase中,我尝试创建一个分组的枚举属性,该属性包含也从PageBase派生的具有不同类型的其他对象。
Now I have singles properties, and I can't use foreach with it. 现在,我具有单打属性,并且无法将它用于它。
public class DiamondListingPage : PageBase
{
public View3x3Tile View3x3Tile { get; set; } = MyPages.View3x3Tile;
public CombTableView CombTableView { get; set; } = MyPages.CombTableView;
public TableView TableView { get; set; } = MyPages.TableView;
}
Instead this three properties I want to use collection of them from other classes, like DiamondListingPage.SubpagesList.TableView instead the current DiamondListingPage.TableView. 相反,这三个属性是我想使用其他类(例如DiamondListingPage.SubpagesList.TableView)中它们的集合,而不是当前的DiamondListingPage.TableView。 And I also want to use foreach for this new collection DiamondListingPage.SubpagesList.
我也想对这个新集合DiamondListingPage.SubpagesList使用foreach。
View3x3Tile, CombTableView, TableView it are different classes derived from PageBase. View3x3Tile,CombTableView,TableView是从PageBase派生的不同类。
If I understand correctly, you want to have class with properties that you can access idividually, but also you want to access some of them grouped in form of a collection so you can use foreach on them. 如果我理解正确,那么您希望拥有一个类,该类具有可以单独访问的属性,而且还希望访问以集合形式分组的某些属性,以便可以在它们上使用foreach 。
You can use the C# iterator method to achieve that. 您可以使用C#迭代器方法来实现。 Theese methods use yield return to return elements of the IEnumerable .
这些方法使用yield return返回IEnumerable的元素。 So the code would look like this:
因此,代码如下所示:
public class DiamondListingPage : PageBase
{
public View3x3Tile View3x3Tile { get; set; } = MyPages.View3x3Tile;
public CombTableView CombTableView { get; set; } = MyPages.CombTableView;
public TableView TableView { get; set; } = MyPages.TableView;
public IEnumerable<PageBase> SubPagesList() {
yield return View3xTitle;
yield return CombTableView;
yield return TableView;
}
}
You can then access specific properties and iterate over them like this: 然后,您可以访问特定属性并像这样遍历它们:
DiamondListingPage x = new DiamondListingPage();
x.View3xTitle = null // accessing individual property
foreach (PageBase p in x.SubPagesList()) {
// do something with p
}
Also in SubPagesList method you can control which properties will be iterated over. 同样,在SubPagesList方法中,您可以控制要迭代的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.