自定义类型的GetEnumerator错误

时间:2015-10-15 13:20:31

标签: c# oop ienumerable

我有以下课程......

class gridRecord
{
    //Constructor
    public gridRecord()
    {
        Quantity = new quantityField();
        Title = new titleField();
        Pages = new pagesField();
    }
    private quantityField quantity;
    private titleField title;
    private pagesField pages;



    internal quantityField Quantity
    {
        get { return quantity; }
        set { quantity = value; }
    }

    internal titleField Title
    {
        get { return title; }
        set { title = value; }
    }

    internal pagesField Pages
    {
        get { return pages; }
        set { pages = value; }
    }
}

我希望能够将每个字段的名称作为字符串获取,以便稍后我可以创建一个数据表而不必指定每个列。

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

foreach(gridField gf in lgr[0])
    MessageBox.Show(gf.ToString());

但是我收到了这个错误:

  

错误1 foreach语句无法对类型变量进行操作   'XML__Console.gridRecord'因为'XML__Console.gridRecord'没有   包含'GetEnumerator'的公共定义

我认为我需要继承表单和界面或其他东西,但不确定如何或哪一个。

Grid Field Added ...

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()
    {

    }
}

在其他字段下方添加的quantityField大致相同

class quantityField : gridField
    {

        public void validate()
        {            
            if (isQuantityValid(Value) == false) { Value = "Invalid";}           
        }

        public static bool isQuantityValid(string quantity)
        {

            if (quantity.Length > 3)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }

3 个答案:

答案 0 :(得分:3)

根据我的理解,您希望从gridRecord类(从您的示例:“数量”,“标题”,“页面”)获取属性的名称?

为此,您需要使用Reflection:

var properties = typeof(gridRecord).GetProperties();
foreach (PropertyInfo propInfo in properties) {
    MessageBox.Show(propInfo.Name);
}

答案 1 :(得分:1)

您正在尝试迭代集合中的一个元素。

foreach(gridField gf in lgr[0])
{
    MessageBox.Show(gf.ToString());
}

如果你的目标是检索班级中每个属性的名称,那么就这样做。

PropertyInfo[] props = typeof(gridRecord).GetProperties();
foreach(PropertyInfo prop in props) 
{
    object[] attrs = prop.GetCustomAttributes(true);
    foreach(object attr in attrs) 
    {
        AuthorAttribute authAttr = attr as AuthorAttribute;
        if (authAttr != null) 
        {
            string propName = prop.Name;
            string auth = authAttr.Name;
        }
    }
}

答案 2 :(得分:0)

如果您想获得每个字段的名称,请使用reflection PropertyInfo课程应该有用