mgravell / fast-member

Automatically exported from code.google.com/p/fast-member
Apache License 2.0
1.02k stars 137 forks source link

Add ability to auto convert from object or string to target property type. #92

Open Korporal opened 3 years ago

Korporal commented 3 years ago

I'm working with a problem in which I must set properties in some object from a string not from a compatibly typed expression.

For example this is valid now:


accessor[instance, "Quantity"] = 123.45M;

where the property Quantity is of type decimal.

but this throws:


accessor[instance, "Quantity"] = 123.45;

as does


accessor[instance, "Quantity"] = "123.45";

So I'd like to see if its feasible to extend this API so that an implicit call is made to Convert.ChangeType to attempt to convert the source to the target type automatically.

In my case it is usually a string source because I'm converting a set of CSV records into anIEnumerable<SomeClass> so in my code I set the property values from a text value found in the relevant CSV column.

Not sure how best you'd expose that but as the API developer that's best left to you, but it would be hugely helpful to be able to set properties from string values rather than from correctly typed source expression.

One idea is to add:

        public abstract string this[object target, string name]
        {
            get;
            set;
        }

or perhaps something like this:

        public abstract object this[object target, string name, bool autoconvert = false]
        {
            get;
            set;
        }

I also don't know if Convert.ChangeType is itself slow and might possibly negate the benefits of the API itself.

What are your thoughts?

Cyril-hcj commented 1 year ago

Are there any conclusions?