Using distinct members of anonymous object-type instances

Sometimes it may happen that you have to set property values on objects depending on whether they exist or not. I though this was feasible using interfaces, but objects can only be checked against contracted interfaces (i.e. such interfaces that occur in the object's class hierarchy), so this is no good here.

An easy way to achieve this is the type.GetProperty() and type.GetProperty().SetValue() methods, as explained below.


PropertyInfo pi = obj.GetType().GetProperty("Enabled");
bool enablable = (pi != null && pi.PropertyType.Equals(typeof(bool)));

if (enablable)
{
obj.GetType().GetProperty( "Enabled" ).SetValue( obj, true, null );
}


The very same thing can also be done with events, methods, fields, nested classes etc. See the following example for an event handler implementation:

EventInfo ei = obj.GetType().GetEvent("Paint");
bool paintable = (ei != null);

if (paintable)
{
PaintEventHandler pe = _Paint;
obj.GetType().GetEvent("Paint").AddEventHandler(obj, pe);
obj.GetType().GetEvent("Paint").RemoveEventHandler(obj, pe);
}

Kommentare

Beliebte Posts aus diesem Blog

WPF Diaries : Using HLSL pixel shaders

Getting the Crisp back into your WPF Apps

WPF and Workflow Foundation : XAML parser compatibility issues