Monday, February 2, 2009

.NET: Reading Property Values using Reflection

class CA
{
private string _myProperty;
public string MyProperty
{
get
{
MyProperty = "Hello"; return MyProperty;
}
}
}


class ReadPropertyGeneric where T : class
{
Type myType;
T _objClass;
public void ReadAndSetProperty(T objClass)
{
myType = (typeof(T));
_objClass = objClass;
// Get the public properties.
PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public BindingFlags.Instance);
Console.WriteLine("The mumber of public properties is {0}.", myPropertyInfo.Length);
// Display the public properties.
DisplayPropertyInfo(myPropertyInfo);
}
public void DisplayPropertyInfo(PropertyInfo[] myPropertyInfo)
{
// Display information for all properties.
for (int i = 0; i < myPropertyInfo.Length; i++)
{
PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i];
Console.WriteLine("The property name is {0}.", myPropInfo.Name);
Console.WriteLine("The property type is {0}.", myPropInfo.PropertyType);
Console.WriteLine("The property value is {0}.", myPropInfo.GetValue(_objClass, null));
object setValueString = myPropInfo.GetValue(_objClass, null) + "NewValue";
myPropInfo.SetValue(_objClass, setValueString, new object[0]);
}
}

No comments:

MSDN: U.S. Local Highlights