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

时间:2015-10-16 09:29:19

标签: c# .net oop ienumerable ienumerator

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

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

但是我会将新的gridField添加到gridRecord类中,并且不想更改正在验证的代码。

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

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

网格记录类......

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 ...

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如果是这样的话?

由于

1 个答案:

答案 0 :(得分:1)

如果你想要这样的代码:

foreach (gridRecord gr in lgr)
{ 
    gr.Validate();
}

Validate的{​​{1}}方法中实现所需内容的一个简单案例(BTW:该类应命名为gridRecord - 类应以大写字符开头到C#命名约定)

GridRecord

但是,如果您要枚举所有字段,则可以使每个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
   }
}