本文介绍了获取作为lambda表达式传递的参数的PropertyInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个课:

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

,我想基于此方法调用此类中的信息更新方法strong> Id :

and I want to call a method to update info in this class base on Id:

update(myId, myPerson => myPerson.Name = "abc");

解释:此方法将从数据库中查询并获取 Person 实体给出了 myId ,然后将 Name 设置为 abc,因此它执行的工作与我所说的相同:

explain: This method will query from database and gets Person entity given a myId, then it sets Name to "abc", so it does the same job as I call this:

update(myId, myPerson => myPerson.Address = "my address");

有可能吗?

推荐答案

这是可能的,不需要使用 PropertyInfo

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

您将设计方法如下:

public bool Update<T>(int id, Action<T> 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;
}

这篇关于获取作为lambda表达式传递的参数的PropertyInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:41