如何转换 PropertyInfo
可用于调用 StructuralTypeConfiguration<TStructuralType>.Ignore<TProperty>(Expression<Func<TStructuralType, TProperty>> propertyExpression)
的属性表达式方法?
我尝试使用 Expression.Property()
构造表达式,但是当我将此表达式用作 propertyExpression
时出现以下错误参数:
The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly.
这个错误可能是指TProperty
我不知道如何指定的类型参数只有 PropertyInfo
.
更新
无效的代码:
var propertyInfo = typeof(Foo).GetProperties()[0];
var expression = Expression.Default(typeof(Foo));
var expressionProperty = Expression.Property(expression, propertyInfo);
Ignore(expressionProperty);
最佳答案
var entityType = propertyInfo.DeclaringType;
var parameter = Expression.Parameter(entityType, "entity");
var property = Expression.Property(parameter, propertyInfo);
var funcType = typeof(Func<,>).MakeGenericType(entityType, propertyInfo.PropertyType);
var lambda = Expression.Lambda(funcType, property, parameter);
structureConfiguration.GetType()
.GetMethod("Ignore")
.MakeGenericMethod(propertyInfo.PropertyType)
.Invoke(structureConfiguration, new[]{lambda});
关于c# - 如何将 PropertyInfo 转换为属性表达式并使用它来调用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9621736/