将强类型属性名称作为参数传递 [英] Passing strongly typed property name as argument

查看:68
本文介绍了将强类型属性名称作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable<School>的集合正在传递给扩展 填充DropDownList的方法.我也想通过 DataValueFieldDataTextField作为参数,但我希望它们成为 强类型.

I have a collection of IEnumerable<School> that is being passed to an extension method that populates a DropDownList. I would also like to pass the DataValueField and DataTextField as an argument but I wanted them to be strongly typed.

基本上,我不想为DataValueFieldDataTextField参数传递string,这很容易出错.

Basically, I don't want to pass a string for the DataValueField and DataTextField arguments, it's error prone.

public static void populateDropDownList<T>(this DropDownList source,
        IEnumerable<T> dataSource,
        Func<T, string> dataValueField,
        Func<T, string> dataTextField) {
    source.DataValueField = dataValueField; //<-- this is wrong
    source.DataTextField = dataTextField; //<-- this is wrong
    source.DataSource = dataSource;
    source.DataBind();
}

这样称呼...

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

我的问题是,如何将强类型化的DataValueFieldDataTextField作为参数传递给populateDropDownList?

My question is, how can I pass the DataValueField and DataTextField strongly typed as an argument to populateDropDownList?

推荐答案

基于乔恩的回答和帖子,它给我一个主意我将DataValueFieldDataTextField作为Expression<Func<TObject, TProperty>>传递给了我的扩展方法.我创建了一个接受该表达式并返回该属性的MemberInfo的方法.然后我只需要打电话给.Name,我就得到了string.

Based off Jon's answer and this post, it gave me an idea. I passed the DataValueField and DataTextField as Expression<Func<TObject, TProperty>> 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.

哦,我将扩展方法名称更改为populate,这很丑.

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

public static void populate<TObject, TProperty>(
        this DropDownList source, 
        IEnumerable<TObject> dataSource, 
        Expression<Func<TObject, TProperty>> dataValueField, 
        Expression<Func<TObject, TProperty>> dataTextField) {
    source.DataValueField = getMemberInfo(dataValueField).Name;
    source.DataTextField = getMemberInfo(dataTextField).Name;
    source.DataSource = dataSource;
    source.DataBind();
}

private static MemberInfo getMemberInfo<TObject, TProperty>(Expression<Func<TObject, TProperty>> expression) {
    var member = expression.Body as MemberExpression;
    if(member != null) {
        return member.Member;
    }
    throw new ArgumentException("Member does not exist.");
}

这样称呼...

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

这篇关于将强类型属性名称作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆