Dynamically Invoking a Member

Once you have a MemberInfo object, you can dynamically call it or get/set its value.

This is called dynamic binding or late binding.

To illustrate, the following uses ordinary static binding:


using System;
using System.Reflection;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        string s = "Hello";
        int length = s.Length;
    }
}

Here's the same thing performed dynamically with reflection:


using System;
using System.Reflection;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        object s = "Hello";
        PropertyInfo prop = s.GetType().GetProperty("Length");
        int length = (int)prop.GetValue(s, null);   // 5
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.