Ron*_*rby 4 c# linq data-binding reflection anonymous-types
我已将ASP.net GridView绑定到匿名类型的集合.
如何在RowDataBound事件处理程序中引用匿名类型的一个属性?
我已经知道像这样强制转换匿名类型的方法:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var AnonObj = Cast(e.Row.DataItem,
new { StringProperty = "", BoolProperty = false, IntProperty = 0 });
if (AnonObj.BoolProperty)
{
e.Row.Style.Add(HtmlTextWriterStyle.Color, "Red");
}
}
}
T Cast<T>(object obj, T type)
{
return (T)obj;
}
Run Code Online (Sandbox Code Playgroud)
我想大多数人会说这很麻烦,尽管它确实有效.在我的真实代码中,我有超过3个属性,我必须在我添加或重新排序我的匿名类型的属性的任何时候更新两个地方的代码.
有没有更好的方法告诉e.Row.DataItem它具有特定类型的特定属性并强制该对象给我该值(除了创建一个类)?
考虑使用反射.
例:
object o = e.Row.DataItem;
Type t = o.GetType();
PropertyInfo pi = t.GetProperty("StringProperty");
if (pi != null && pi.PropertyType == typeof(string))
{
// the property exists!
string s = pi.GetValue(o, null) as string;
// we have the value
// insert your code here
// PROFIT! :)
}
Run Code Online (Sandbox Code Playgroud)
错误检查和优化留给读者练习.
| 归档时间: |
|
| 查看次数: |
4391 次 |
| 最近记录: |