How can I pass a property as a delegate?

前端 未结 6 1551
深忆病人
深忆病人 2021-02-04 04:03

This is a theoretical question, I\'ve already got a solution to my problem that took me down a different path, but I think the question is still potentially interesting.

6条回答
  •  灰色年华
    2021-02-04 04:53

    I like using expression trees to solve this problem. Whenever you have a method where you want to take a "property delegate", use the parameter type Expression>. For example:

    public void SetPropertyFromDbValue(
        T obj,
        Expression> expression,
        TProperty value
    )
    {
        MemberExpression member = (MemberExpression)expression.Body;
        PropertyInfo property = (PropertyInfo)member.Member;
        property.SetValue(obj, value, null);
    }
    

    Nice thing about this is that the syntax looks the same for gets as well.

    public TProperty GetPropertyFromDbValue(
        T obj,
        Expression> expression
    )
    {
        MemberExpression member = (MemberExpression)expression.Body;
        PropertyInfo property = (PropertyInfo)member.Member;
        return (TProperty)property.GetValue(obj, null);
    }
    

    Or, if you're feeling lazy:

    public TProperty GetPropertyFromDbValue(
        T obj,
        Expression> expression
    )
    {
        return expression.Compile()(obj);
    }
    

    Invocation would look like:

    SetPropertyFromDbValue(myClass, o => o.Property1, reader["field1"]);
    GetPropertyFromDbValue(myClass, o => o.Property1);
    

提交回复
热议问题