dimanche 15 décembre 2019

Adding universal getter/setter for all calls to child object/Generating methods at runtime

Preamble: I'm working on implementing a system where a developer can specify on object of type T which has N number of properties.

What I'm trying to accomplish:

I'd like to be able to provide more concrete control over how these properties are set and retrieved. This is difficult because of the limitless number of configurations possible.

Solutions I'm pursuing:

  • Is it possible to set getters dynamically?
  • Either through attributes? Generate the methods after the fact during construction like :
    foreach(var property in typeOf(T).GetProperties()) 
    {
         //dynamically generate getter method which returns this property.
    }
  • Possibly wrap type T in a container object which has the type as one of its properties. Then set up some type of special getter for that.

Why I want to do this:

Currently all the types for T get converted based on Typecode. Allowing people using this library to easily parse in values from various sources (databases, text files, app configs, etc.) as properties of type T. The point being to deliver these properties as type safe values rather than magic strings.

This is the impetus for wanting to use reflection for this but I could see numerous other applications for this I would imagine.

I could just say "Hey make all of your types nullable." so that it would be easy to determine which properties have been set in type T. I'd like to abstract away even that though.

The other option for this would be "Make sure you understand that certain types have default values. Be certain you're ready to accept those values, or set default values of your own (including making it nullable and setting it to null if so desired). Essentially trusting this to the developer rather than abstracting it. <==== This is what I'm currently doing.

Being able to dynamically generate methods, especially getters and setters, dynamically via reflection or a combination of reflection and C# Actions would be incredibly valuable. Any insight or ideas would be greatly welcome. Either ways of accomplishing the solutions I'm pursuiing or another idea which achieves the same ends.





Aucun commentaire:

Enregistrer un commentaire