我希望能够像这样调用这个方法:
test.TestMethod<From, To>(to => to.Prop1);
并具有来自To的IDE自动完成属性。在TestMethod
中,我想提取属性的名称。在这种情况下Prop1
。这似乎是一种工作,但我不确定Expression<Func<TTo, object>>
,尤其是对象部分。
public class Test
{
public void TestMethod<TFrom, TTo>(Expression<Func<TTo, object>> p)
{
}
}
如果我通过p递归,它会做到它应该做的事情,我可以得到这个名字,但它并不适合我,特别是因为拉出道具的名字看起来像:
((MemberExpression)((UnaryExpression)(((LambdaExpression)p).Body)).Operand)).Member.Name
有什么方法可以做到更清洁?
答案 0 :(得分:0)
这是一个帮助器类,它将检查表达式并提取属性的成员信息
fit_predict(X[, y]): Performs clustering on X and returns cluster labels.
predict(X): Predict the closest cluster each sample in X belongs to.
然后您可以按预期提取名称......
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Extension for <see cref="Expression"/>.
/// </summary>
public static class ExpressionExtensions {
/// <summary>
/// Converts an expression into a <see cref="System.Reflection.MemberInfo"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>The member info.</returns>
public static MemberInfo GetMemberInfo(this Expression expression) {
var lambda = (LambdaExpression)expression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression) {
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
memberExpression = (MemberExpression)lambda.Body;
return memberExpression.Member;
}
}
然后您就可以像这样调用此方法......
public class Test {
public void TestMethod<TFrom, TTo>(Expression<Func<TTo>> property) {
var memberName = property.GetMemberInfo().Name;
//...other code
}
}
...并获取属性名称。