How to create lambda expression that returns object's property, having this property's name?

后端 未结 2 1857
清酒与你
清酒与你 2021-01-22 09:39

I am completely lost on this one. I have a piece of code that does what I need when implemented like this:

return filters.Add(m => m.Metadata.RecordId).IsEqua         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 10:34

    What about this call:

    return filters.Add(m => ReflectionMagic(m, "Metadata.RecordId").IsEqualTo(1);
    

    The method would have this signature:

    public object ReflectionMagic(object source, string property);
    

    If that would work, you could do something like this:

    var propertyTree = property.Split('.');
    
    foreach(var propertyName in propertyTree)
    {
         var propInfo = source.GetType().GetProperty(propertyName);
         var source = propInfo.GetValue(source, null);
    }
    
    return source;
    

    Be aware that any kind of argument and return value checks are missing and are left as an excercise to the reader.

提交回复
热议问题