foreach statement cannot operate on variables of type 'object'

This question already has an answer here:

  • How to Casting DataSource to List<T>? 4 answers

  • If you do not know the exact type of object, but you know for sure that whatever it is, it will have GetEnumerator on it (say, because it's a collection or one of your own objects that implements IEnumerable ) you can stop the compiler from issuing an error by casting to dynamic , like this:

    foreach (var item in (dynamic)(ddlOther.DataSource)) {
        ...
    }
    

    The trade-of here is that if it turns out that ddlOther.DataSource does not have GetEnumerator , you will get an error at runtime, rather than a compile-time error.


    Modify your code to check on the IEnumerable interface. It have the feeling underlying correction is more what you want.

    public void DataSource(object source, object select, string Value = "UId", string Text = "Text")
    {
        ddlThis.DataSource = source;
        ddlThis.DataTextField = Text;
        ddlThis.DataValueField = Value;
        ddlThis.DataBind();
    
        ddlThisHidden.DataSource = source;
        ddlThisHidden.DataTextField = Text;
        ddlThisHidden.DataValueField = Value;
        ddlThisHidden.DataBind();
    
        if (select != null)
        {
            ddlOther.DataSource = select;
            ddlOther.DataTextField = Text;
            ddlOther.DataValueField = Value;
            ddlOther.DataBind();
    
            if (select is IEnumerable) //check if the object is a list of objects
                foreach (var item in (IEnumerable)ddlOther.DataSource)
                    ddlThis.Items.Remove(item);
            else //try to remove the single object
                ddlThis.Items.Remove(select)
        }
    }
    
    链接地址: http://www.djcxy.com/p/53764.html

    上一篇: 用Java字节码编程

    下一篇: foreach语句不能对'object'类型的变量进行操作