Invoking a static method with Reflection


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Invoking a static method with Reflection

Hybrid View

  1. #1
    Staffan Guest

    Invoking a static method with Reflection


    I like to invoke a static method "getInstance" on a class using C#. Any ideas?
    This won't work...

    Assembly a = Assembly.LoadFrom("Reflection.dll");
    Type t = a.GetType("Reflection.Singleton");
    MethodInfo mi = t.GetMethod("getInstance");
    object o = mi.Invoke(t, new object[]{});

    Thanks
    /Staffan

  2. #2
    Patrick Steele [MVP] Guest

    Re: Invoking a static method with Reflection

    In article <3ec114e5$1@tnews.web.devx.com>, st_rosengren@hotmail.com
    says...
    >
    > I like to invoke a static method "getInstance" on a class using C#. Any ideas?
    > This won't work...
    >
    > Assembly a = Assembly.LoadFrom("Reflection.dll");
    > Type t = a.GetType("Reflection.Singleton");
    > MethodInfo mi = t.GetMethod("getInstance");
    > object o = mi.Invoke(t, new object[]{});


    Try:

    MethodInfo mi = t.GetMethod("getInstance", BindingFlags.Static);

    --
    Patrick Steele
    Microsoft .NET MVP
    http://radio.weblogs.com/0110109

  3. #3
    Staffan Guest

    Re: Invoking a static method with Reflection


    Patrick Steele [MVP] <patrick@mvps.org> wrote:
    >In article <3ec114e5$1@tnews.web.devx.com>, st_rosengren@hotmail.com
    >says...
    >>
    >> I like to invoke a static method "getInstance" on a class using C#. Any

    ideas?
    >> This won't work...
    >>
    >> Assembly a = Assembly.LoadFrom("Reflection.dll");
    >> Type t = a.GetType("Reflection.Singleton");
    >> MethodInfo mi = t.GetMethod("getInstance");
    >> object o = mi.Invoke(t, new object[]{});

    >
    >Try:
    >
    >MethodInfo mi = t.GetMethod("getInstance", BindingFlags.Static);
    >
    >--
    >Patrick Steele
    >Microsoft .NET MVP
    >http://radio.weblogs.com/0110109


    Thanks, although it didn't work. But I could simply do like this...

    Type t = t.GetType("Reflection.Singelton");
    object o = t.InvokeMember("getInstance", BindingFlags.InvokeMethod, null,
    t, new object[0]);


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center