Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Case-insentive property setter
Message
De
25/03/2007 15:16:57
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Titre:
Case-insentive property setter
Versions des environnements
Environment:
VB 8.0
Divers
Thread ID:
01208319
Message ID:
01208319
Vues:
51
I use modified Rockford Lhotka excellent SetPropertyValue()
from DataMapper class to load objects from database.
My entity object property names are mixed case.
DataReader returns lower-case only column names.
So SetPropertyValue() cannot map columns to property names.

How to change this code so that it does not depend on the propertyName case ?
/// <summary>
/// Sets an object's property with the specified value,
/// coercing that value to the appropriate type if possible.
/// </summary>
/// <param name="target">Object containing the property to set.</param>
/// <param name="propertyName">Name of the property to set.</param>
/// <param name="value">Value to set into the property.</param>
public static void SetPropertyValue(
   object target, string propertyName, object value)
 {
   PropertyInfo propertyInfo =
        target.GetType().GetProperty(propertyName);
   if (value == null)
        propertyInfo.SetValue(target, value, null);
   else
      {
        Type pType =
          Utilities.GetPropertyType(propertyInfo.PropertyType);
        Type vType =
          Utilities.GetPropertyType(value.GetType());
        if (pType.Equals(vType))
        {
          // types match, just copy value
          propertyInfo.SetValue(target, value, null);
        }
        else
        {
          // types don't match, try to coerce
          if (pType.Equals(typeof(Guid)))
            propertyInfo.SetValue(
              target, new Guid(value.ToString()), null);
          else if (pType.IsEnum && vType.Equals(typeof(string)))
            propertyInfo.SetValue(target, Enum.Parse(pType, value.ToString()), null);
					else if (pType.IsEnum && vType.Equals(typeof(decimal)))
						propertyInfo.SetValue(target, 
							Enum.Parse(pType, value.ToString()), null);

					else
            propertyInfo.SetValue(
              target, Convert.ChangeType(value, pType), null);
        }
      }
    }
  }
}
Andrus
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform