How can I pass a property as a delegate?

前端 未结 6 1539
深忆病人
深忆病人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 04:47

    (Adding a second answer because it's on a completely different approach)

    To address your original problem, which is more about wanting a nice API for mapping named values in a datareader to properties on your object, consider System.ComponentModel.TypeDescriptor - an often overlooked alternative to doing reflective dirtywork yourself.

    Here's a useful snippet:

    var properties = TypeDescriptor.GetProperties(myObject)
        .Cast()
        .ToDictionary(pr => pr.Name);
    

    That creates a dictionary of the propertydescriptors of your object.

    Now I can do this:

    properties["Property1"].SetValue(myObject, rdr["item1"]);
    

    PropertyDescriptor's SetValue method (unlike System.Reflection.PropertyInfo's equivalent) will do type conversion for you - parse strings as ints, and so on.

    What's useful about this is one can imagine an attribute-driven approach to iterating through that properties collection (PropertyDescriptor has an Attributes property to allow you to get any custom attributes that were added to the property) figuring out which value in the datareader to use; or having a method that receives a dictionary of propertyname - columnname mappings which iterates through and performs all those sets for you.

    I suspect an approach like this may give you the API shortcut you need in a way that lambda-expression reflective trickery - in this case - won't.

提交回复
热议问题