mardi 8 mai 2018

How to dynamically get the instance of an object's property using reflection

I have found lots of examples that ALMOST tell me what I need to know. But everything so far assumes I already have an instance of the property that I want to set the value. But I don't have an instance. I have a PropertyInfo object. I can dynamically obtain the name of the property but in order to call SetValue() I must have an instance of the property to pass to the method. How do I get an instance of the property whose value I need to set? Here is my code with ??? where an instance of the property must be provided. How do I get an instance of the property and not just a PropertyInfo object? (The reason I am writing this method is because I cannot guarantee which columns various stored procedures will return.)

    protected new void MapDbResultToFields(DataRow row, DataColumnCollection columns)
    {
        Console.WriteLine("Entered Clinician.MapDbResultToFields");
        var properties = this.GetType().GetProperties();
        Console.WriteLine("Properties Count: " + properties.Length);
        foreach (DataColumn col in columns)
        {
            Console.WriteLine("ColumnName: " + col.ColumnName);
        }
        foreach (var property in properties)
        {
            string propName = property.Name.ToLower();
            Console.WriteLine("Property name: " + propName);
            Console.WriteLine("Index of column name: " + columns.IndexOf(propName));
            Console.WriteLine("column name exists: " + columns.Contains(propName));
            if (columns.Contains(propName))
            {
                Console.WriteLine("PropertyType is: " + property.PropertyType);
                switch (property.PropertyType.ToString())
                {
                    case "System.String":
                        String val = row[propName].ToString();
                        Console.WriteLine("RowColumn Value (String): " + val);
                        property.SetValue(???, val, null);
                        break;
                    case "System.Nullable`1[System.Int64]":
                    case "System.Int64":
                        Int64.TryParse(row[propName].ToString(), out var id);
                        Console.WriteLine("RowColumn Value (Int64): " + id);
                        property.SetValue(???, id, null);
                        break;
                    case "System.Boolean":
                        Boolean.TryParse(row[propName].ToString(), out var flag);
                        Console.WriteLine("RowColumn Value (Boolean): " + flag);
                        property.SetValue(???, flag, null);
                        break;
                }

            }
            else
            {
                Console.WriteLine("Property name not found in columns list");
            }
        }
}





Aucun commentaire:

Enregistrer un commentaire