Passing strongly typed property name as argument

后端 未结 3 1198
春和景丽
春和景丽 2020-12-30 17:37

I have a collection of IEnumerable that is being passed to an extension method that populates a DropDownList. I would also like to pa

3条回答
  •  半阙折子戏
    2020-12-30 17:57

    Based off Jon's answer and this post, it gave me an idea. I passed the DataValueField and DataTextField as Expression> to my extension method. I created a method that accepts that expression and returns the MemberInfo for that property. Then all I have to call is .Name and I've got my string.

    Oh, and I changed the extension method name to populate, it was ugly.

    public static void populate(
            this DropDownList source, 
            IEnumerable dataSource, 
            Expression> dataValueField, 
            Expression> dataTextField) {
        source.DataValueField = getMemberInfo(dataValueField).Name;
        source.DataTextField = getMemberInfo(dataTextField).Name;
        source.DataSource = dataSource;
        source.DataBind();
    }
    
    private static MemberInfo getMemberInfo(Expression> expression) {
        var member = expression.Body as MemberExpression;
        if(member != null) {
            return member.Member;
        }
        throw new ArgumentException("Member does not exist.");
    }
    

    Called like so...

    myDropDownList.populate(states,
        school => school.stateCode,
        school => school.stateName);
    

提交回复
热议问题