Here's a useful extension you can add to an object.
public static class Extensions { public static void SetPropertiesToValue(this object obj, string propertyNameStartsWith, Type propertyType, object val) { foreach (PropertyInfo prop in obj.GetType().GetProperties()) { if (prop.Name.StartsWith(propertyNameStartsWith) && prop.PropertyType == propertyType && prop.CanWrite) prop.SetValue(obj, val); } } }
And here's how to use it:
myObj.SetPropertiesToValue("Name", typeof(string), "Jim");This will set any property of myObj that has a name starting with Name to Jim.
No comments:
Post a Comment