Pass property itself to function as parameter in C#

后端 未结 7 1609
春和景丽
春和景丽 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 19:55

    Great solution over here...

    Passing properties by reference in C#

    void GetString(string input, T target, Expression> outExpr)
    {
        if (!string.IsNullOrEmpty(input))
        {
            var expr = (MemberExpression) outExpr.Body;
            var prop = (PropertyInfo) expr.Member;
            prop.SetValue(target, input, null);
        }
    }
    
    void Main()
    {
        var person = new Person();
        GetString("test", person, x => x.Name);
        Debug.Assert(person.Name == "test");
    }
    

提交回复
热议问题