mardi 7 août 2018

Itterating through a dictionary and setting a value using Reflections in C#

I have an object that looks like this.

{MoCApp.Models.Item}
    Approved: null
    Brand: "Disco"
    CtCost: null
    CtPack: 40
    DateApproved: null
    DateRequested: {}
    DateReviewed: null
    Dep: null

If it is null value I would like to change to a string "Null" if it is a string type, and if it is an int type I would like to change to 00000

So far I have

        foreach(var prop in item.GetType().GetProperties())
        {
            if (prop.GetValue(item) == null)
            {
                if (prop.PropertyType == typeof(string))
                {
                   // I dont know how to set the value here!  Please help!
                   // I want to set the value in the key value pair to "Null"

                }
                if (prop.PropertyType == typeof(int))
                {
                    // and here I want to set the value to 00000 when the prop type is int

                }
            }

            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(item, null));
            System.Diagnostics.Debug.WriteLine("{0}, {1}, {2}", prop.Name, prop.GetValue(item), prop.PropertyType);
        }





Aucun commentaire:

Enregistrer un commentaire