jeudi 3 décembre 2020

How to get the assigned properties of an object initializer using reflection?

I have classes that specify hard coded values. An example looks like the following:

    [CodeGenAsValueObject]
    public class DfltTaxableTypes : WithEnumerablePropsOfType<TaxableType>
    {
        public static TaxableType Taxable = new TaxableType()
        {    // <-  I want what's inside of here specifically as Dict<string, object>
            TaxableTypeId = new Guid("7a702ec4-94a3-431b-8217-2b44ef0ae22a"),
            Name = "Taxable"
        };   //  <-  To here

        public static TaxableType NonTaxable = new TaxableType()
        {
            TaxableTypeId = new Guid("76eee771-cbdc-4a7b-95d5-0d6e0959bdff"),
            Name = "NonTaxable"
        };
    }

Assume TaxableType has many properties that otherwise I don't care about.

How can I using reflection get something like a Dictionary<string, object> of assigned properties for each static TaxableType?

I am using this in custom Code Generation for our Typescript clients so performance is not an issue.

What I have as a start:

    var dfltValObjContainers = myAssy.GetTypes()
        .Where(x => x.CustomAttributes.Select(y => y.AttributeType)
            .ToList()
            .Contains(typeof(CodeGenAsValueObject)))
        .Distinct().ToList();
    
    var containerInstances= dfltValObjContainers.Select(x => {
            var instance = Activator.CreateInstance(x);
            // Could get all Fields' values where value != default(fieldType).. 
            // Would prefer a more direct get assigned properties of object initializer.
            var eaValueObj = x.GetFields().Select(f => {
                return f.GetObjectInitializersAsDict() // <- Need help here.
            }).ToList();
        }).ToList();





Aucun commentaire:

Enregistrer un commentaire