让我的类型像列表一样工作

Make my Type work like a list

我已经创建了我自己的类型列表...(Class页面底部的自定义类型)

List<gridRecord> lgr = new List<gridRecord>();
lgr = populatedList();

我用下面的代码验证列表中的每个字段...(这很好用!)

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 Class 添加新的 gridFields,并且不想更改正在验证的代码。

所以...我希望能够做这样的事情...

foreach (gridField gf in lgr)
{ 
    gf.Validate();
}

网格记录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()
    {

    }
}

网格字段Class...

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();
}

这是在 gridRecordValidate 方法中实现所需内容的简单案例(顺便说一句: class 应该命名为 GridRecord - class根据 C# 命名约定,es 应以大写字符开头)

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();
    }
}