将MemberExpression应用于对象以检索Property值

时间:2015-12-16 05:44:11

标签: c# linq

我正在尝试编写一个泛型函数,它接受一个MemberExpression和一个对象,并返回成员表达式中定义的Property的值。

以下是获取Property name的代码示例。

import android.app.*;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;

public class ShowPopUp extends Activity {

PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
Button but;
boolean click = true;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    popUp = new PopupWindow(this);
    layout = new LinearLayout(this);
    mainLayout = new LinearLayout(this);
    tv = new TextView(this);
    but = new Button(this);
    but.setText("Click Me");
    but.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            if (click) {
                popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
                popUp.update(50, 50, 300, 80);
                click = false;
            } else {
                popUp.dismiss();
                click = true;
            }
        }

    });
    params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    tv.setText("Hi this is a sample text for popup window");
    layout.addView(tv, params);
    popUp.setContentView(layout);
    // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
    mainLayout.addView(but, params);
    setContentView(mainLayout);
       }
   }

但我想从模型中检索属性的值:

 if (!empty($collection) && is_array($collection)) {

}

我称之为此功能的方式是:

public static TProperty GetPropertyName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, TModel model)
{
    if (expression.Body is MemberExpression)
    {
        return ((MemberExpression)expression.Body).Member.Name;
    }
    else
    {
        var op = ((UnaryExpression)expression.Body).Operand;
        return ((MemberExpression)op).Member.Name;
    }
}

1 个答案:

答案 0 :(得分:3)

MemberExpression是指MemberInfo,如果是属性表达式,则为PropertyInfo

static class MemberExpressionHelper
{
    public static TProperty GetPropertyValue<TModel, TProperty>(TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        // case with `UnaryExpression` is omitted for simplicity
        var memberExpression = (MemberExpression)expression.Body;

        var propertyInfo = (PropertyInfo)memberExpression.Member;
        return (TProperty)propertyInfo.GetValue(model);
    }
}

此外,交换参数更自然(首先是model,第二是表达式)。作为副作用,这允许编译器推断类型参数:

var bar = MemberExpressionHelper.GetPropertyValue(foo, _ => _.Bar);