代码:
foreach (PropertyInfo prop in typeof(SomeObject).GetProperties())
{
if (Attribute.IsDefined(prop, typeof(SomeCustomAttribute)))
{
column.Expression(p => p.Name);
}
}
我想添加分配了SomeCustomAttribute数据注释的列。
如何使用prop.Name(属性的名称)作为属性而不是手动p.Name?
例如......
...
column.Expression(p => prop.Name);
...
column.Expression是
ITableColumn Expression<TProperty>(Expression<Func<TModel, TProperty>> expression)
答案 0 :(得分:2)
假设您已定义此类型:
interface ITableColumn { }
class SomeObject
{
public int MyProperty { get; set; }
}
class Column<TModel>
{
public ITableColumn Expression<TProperty>(Expression<Func<TModel, TProperty>> expression)
{
// just a stub
return null;
}
}
要通过反射获取单个属性Column.Expression
,您必须首先构建成员表达式:
private static LambdaExpression MakeMemberExpression(PropertyInfo propertyInfo)
{
var instanceExpression = Expression.Parameter(propertyInfo.DeclaringType);
return Expression.Lambda(Expression.MakeMemberAccess(instanceExpression, propertyInfo), instanceExpression);
}
只要您不静态地知道TProperty
,就不需要构建强类型lambda(Expression<Func<TModel, TProperty>>
)。
现在,让我们调用它:
var property = typeof(SomeObject)
.GetProperty("MyProperty");
var columnType = typeof(Column<>)
.MakeGenericType(typeof(SomeObject));
var expressionMethod = columnType
.GetMethod("Expression")
.MakeGenericMethod(property.PropertyType);
var expr = MakeMemberExpression(property);
expressionMethod.Invoke(new Column<SomeObject>(), new[] { expr });
希望这有帮助。