我有一个收藏IEnumerable<School>
正在传递给扩展
填充的方法DropDownList
。我也想通过DataValueField
and DataTextField
作为一个论据,但我希望它们是
强类型。
基本上,我不想通过string
为了DataValueField
and DataTextField
争论,很容易出错。
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);
我的问题是,我怎样才能通过DataValueField
and DataTextField
强类型作为填充下拉列表的参数?
根据乔恩的回答和this帖子,它给了我一个想法。我通过了DataValueField
and DataTextField
as Expression<Func<TObject, TProperty>>
到我的扩展方法。我创建了一个接受该表达式并返回的方法MemberInfo
对于该财产。那么我所要做的就是打电话.Name
我有我的string
.
哦,我将扩展方法名称更改为populate
,很丑。
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)