Get PropertyInfo of a parameter passed as lambda expression

前端 未结 4 1792
攒了一身酷
攒了一身酷 2021-01-11 14:49

For example, I have a class:

public class Person
{
  public int Id;
  public string Name, Address;
}

and I want to call a method to update

4条回答
  •  借酒劲吻你
    2021-01-11 15:32

    This is possible, and there's no need to use PropertyInfo.

    You'd design your method like so:

    public bool Update(int id, Action updateMethod)
        // where T  : SomeDbEntityType
    {
        T entity = LoadFromDatabase(id); // Load your "person" or whatever
    
        if (entity == null) 
            return false; // If you want to support fails this way, etc...
    
        // Calls the method on the person
        updateMethod(entity);
    
        SaveEntity(entity); // Do whatever you need to persist the values
    
        return true;
    }
    

提交回复
热议问题