【发布时间】:2021-07-29 00:18:39
【问题描述】:
我目前正在探索封装一些通常是迭代的逻辑的可行性。使用第 3 方库,它具有通用 Html Helper 方法,允许您将属性从 Generic T 类映射到表组件。通常你必须写一些东西来达到以下效果:
HtmlHelper.GenerateTable<ClassName>
.configure(tableDefinition =>{
// Adding each property you want to render here
tableDefinition.add(myClassRef => myClassRef.propertyA);
tableDefinition.add(myClassRef => myClassRef.propertyB);
})
我正在探索将属性添加到标准 Display 属性等属性的想法,然后使用反射将该属性添加到容器中。 add 方法只接受 Expression<Func<T, TValue>> 类型的参数。根据我目前对反射的理解,我知道我可以通过循环 PropertyInfo 并使用 GetCustomAttribute 检查我想要的属性来识别适用的属性。
我感到困惑的是,是否可以使用反射来提供 add 方法所期望的参数类型?
我将抛出到目前为止我已经开始使用的辅助方法逻辑。我的假设是,这将引导我走向 Expression 和 Lambda 类,但我无法充实任何有效的东西,因为我在技术上没有 TValue。
var t = typeof(T);
List<PropertyInfo> properties = t.GetProperties().ToList();
foreach(var prop in properties)
{
var attr = (DisplayAttribute[])prop.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attr.Length > 0)
{
// TODO: Call add with expression?
}
}
【问题讨论】:
标签: c# .net reflection