Pass property itself to function as parameter in C#

后端 未结 7 1615
春和景丽
春和景丽 2020-12-12 19:25

I am looking for a method to pass property itself to a function. Not value of property. Function doesn\'t know in advance which property will be used for sorting. Simplest w

7条回答
  •  Happy的楠姐
    2020-12-12 19:36

    What I found missing from @MatthiasG's answer is how to get property value not just its name.

    public static string Meth(Expression> expression)
    {
        var name = ((MemberExpression)expression.Body).Member.Name;
        var value = expression.Compile()();
        return string.Format("{0} - {1}", name, value);
    }
    

    use:

    Meth(() => YourObject.Property);
    

提交回复
热议问题