mardi 15 octobre 2019

C# - Initializing an immutable class with reflection

I have a class that has readonly properties. I am trying to not add setters to it and would prefer that it can be created with the correct values and never changed after.

public class Stuff 
{
    public decimal Price { get; }
    public string Name { get; }
    public Stuff(decimal price, string name)
    {
        Price = price;
        Name = name;
    }
}

The problem is I may also have a few different classes of this nature. I want to be able to map properties from one text format to actual objects. But I can't use reflection to access the property's set method because there will be none.

That leaves the option of getting the constructor and invoking it. That would be great and all but I don't see a reliable method to retrieve the constructor. The best I see would be passing in a type array to get that specific constructor.

var props = typeof(T).GetProperties().Select(p => p.PropertyType).ToArray();
var constructor = typeof(T).GetConstructor(props);

The above may return null depending on the order of the properties. I'm mainly looking for a way to get the constructor, loop through its params by name and order my inputs as necessary.

I know the framework supports serializing and deserializing these kinds of classes so it must be possible. I am just not sure how it's being done.





Aucun commentaire:

Enregistrer un commentaire