Ниже я написал класс-оболочку, который вы можете использовать для установки / получения открытых полей или свойств упакованного класса по строковому имени.
Сначала давайте посмотрим, как вы можете использовать его в классе с открытыми полями или свойствами StartDate и SocialSecurityNumber.
// First create the instance we'll want to play with
MyUserControl myControlInstance = new MyUsercontrol();
// MyUserContol has two properties we'll be using
// DateTime StartDate
// int SocialSecurityNumber
// Now we're creating a map to facilitate access to the properties
// of "myControlInstance" using strings
PropertyMap<MyUserControl> map =
new PropertyMap<MyUserControl>(myControlInstance);
// Since the map is directed toward "myControlInstance"
// this line is equivalent to:
// myControlInstance.StartDate = Datetime.Now;
map.Set<DateTime>("StartDate", DateTime.Now);
// This line is equivalent to:
// ssn = myUsercontrol.SocialSecurityNumber;
int ssn = map.Get<int>("SocialSecurityNumber");
А теперь о том, как это реализовано:
public class PropertyMap<T>
{
readonly T Instance;
public PropertyMap(T instance)
{
Instance = instance;
}
public U Get<U>(string PropertyName)
{
// Search through the type's properties for one with this name
// Properties are things with get/set accessors
PropertyInfo property = typeof(T).GetProperty(PropertyName);
if (property == null)
{
// if we couldn't find a property, look for a field.
// Fields are just member variables, but you can only
// manipulate public ones like this.
FieldInfo field = typeof(T).GetField(PropertyName);
if (field == null)
throw new Exception("Couldn't find a property/field named " + PropertyName);
return (U)field.GetValue(Instance);
}
return (U)property.GetValue(Instance, null);
}
public void Set<U>(string PropertyName, U value)
{
// Search through the type's properties for one with this name
PropertyInfo property = typeof(T).GetProperty(PropertyName);
if (property == null)
{
// if we couldn't find a property, look for a field.
FieldInfo field = typeof(T).GetField(PropertyName);
if (field == null)
throw new Exception("Couldn't find a property/field named " + PropertyName);
field.SetValue(Instance, value);
return;
}
property.SetValue(Instance, value, null);
}
}