Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Case-insentive property setter
Message
De
25/03/2007 20:44:05
 
 
À
25/03/2007 15:16:57
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
VB 8.0
Divers
Thread ID:
01208319
Message ID:
01208351
Vues:
19
Andrus,

I guess Rocky's class needs a little more ooomph. <g>

After a little experimenting, this works:
   PropertyInfo propertyInfo =
       target.GetType().GetProperty(propertyName, System.Reflection.BindingFlags.Instance | 
                        System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public)
Apparently you need *all* the BindingFlags ... just the IgnoreCase by itself doesn't work.

~~Bonnie



>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);
>        }
>      }
>    }
>  }
>}
>
Bonnie Berent DeWitt
NET/C# MVP since 2003

http://geek-goddess-bonnie.blogspot.com
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform