让我的类型像列表一样工作
本文关键字:一样 工作 我的 类型 列表 | 更新日期: 2023-09-27 18:18:02
我已经创建了一个我自己的类型列表…(类的自定义类型在页面底部)
List<gridRecord> lgr = new List<gridRecord>();
lgr = populatedList();
我用下面的代码验证List中的每个字段…
foreach (gridRecord gr in lgr)
{
gr.Quantity.validate();
gr.Title.validate();
gr.Pages.validate();
dt.Rows.Add(gr.Title.Value.ToString(), gr.Quantity.Value.ToString(), gr.Pages.Value.ToString());
}
然而,我将在gridRecord类中添加新的gridFields,并且不想更改验证的代码。
所以…我希望能够做这样的事情……
foreach (gridField gf in lgr)
{
gf.Validate();
}
grid Record Class…
class gridRecord : Validateit
{
//Constructor
public gridRecord()
{
Quantity = new quantityField();
Title = new titleField();
Pages = new pagesField();
}
private quantityField quantity;
private titleField title;
private pagesField pages;
public quantityField Quantity
{
get { return quantity; }
set { quantity = value; }
}
public titleField Title
{
get { return title; }
set { title = value; }
}
public pagesField Pages
{
get { return pages; }
set { pages = value; }
}
public override void Validate()
{
}
}
gridField类…
class gridField : Validateit
{
public gridField()
{
Value = "---";
isValid = false;
message = "";
}
private string value;
protected bool isValid;
private string message;
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public bool IsValid
{
get { return isValid; }
set { isValid = value; }
}
public string Message
{
get { return message; }
set { message = value; }
}
public override void Validate()
{
}
}
我需要使用IEnumerable
,如果是这样,如何?
谢谢
如果你想要这样的代码:
foreach (gridRecord gr in lgr)
{
gr.Validate();
}
这是在gridRecord
的Validate
方法中实现所需的一个简单案例(BTW:该类应命名为GridRecord
-类应根据c#命名约定以大写字符开头)
class gridRecord : Validateit
{
//.. snip
public override void Validate()
{
this.Quantity.Validate();
this.Title.Validate();
this.Pages.Validate();
}
}
但是,如果您希望枚举所有字段,您可以使每个gridRecord
像这样实现IEnumerable<gridField>
:
class gridRecord : Validateit, IEnumerable<gridField>
{
//.. snip
public IEnumerator<gridField> GetEnumerator()
{
yield return Quantity;
yield return Title;
yield return Pages;
}
public IEnumerator GetEnumerator()
{
return GetEnumerator(); // generic version
}
}
你可以写这样的代码:
foreach (gridRecord gr in lgr) // enumerate each record
{
foreach(gridField gf in gr) // enumerate each field within each record
{
gf.Validate();
}
}