When Reflection Attacks!

Just been reading a post by Geoff Appleby on the pros and cons of reflection. He also points to a very interesting use of reflection by Darren Neimke to control the routing of messages within a system like BizTalk.
I have similar reservations to using reflection that Geoff has - mainly because I came from a Java world where reflection could just totally kill performance. However I also agree that there's some situations where it's just incredibly useful - I recently used reflection in an application which uses User Controls to provide functionality, well occasionally I had to set some specific properties on controls (just let me reuse the same control with different properties set..) here's the code I use

private void SetCustomProperties(UserControl uctrl, FControl defCtrl)

        {

            Type uctrlType = uctrl.GetType().BaseType;

            if (defCtrl.Settings != null && defCtrl.Settings.Count > 0)

            {

                foreach (string s in defCtrl.Settings.AllKeys)

                {

                    PropertyInfo theProperty = uctrlType.GetProperty(s);

                    if (theProperty != null)

                    {

                        object val = null;

                        Type testType = theProperty.PropertyType;

                        if (testType.IsEnum)

                            val = Convert.ChangeType(Enum.Parse(testType, defCtrl.Settings[s]), testType);

                        else

                            val = Convert.ChangeType(defCtrl.Settings[s], testType);

                        if (val != null)

                            theProperty.SetValue(uctrl, val, null);

                    }

                }

            }

        }

 

So, obviously lots of wierd custom classes and stuff but you can probably see it's actually pretty simple in the end.

Print | posted @ Thursday, January 20, 2005 10:32 AM

Comments on this entry:

Gravatar # re: When Reflection Attacks!
by Geoff Appleby at 1/20/2005 10:57 AM

Hey man. Cool :)

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 4 and 1 and type the answer here: