Activator and static classes
Asked Answered
P

5

14

I'm tossing around the idea of using the Activator class in order to get access to resources in an assembly that I would otherwise create a circular reference for (dependency injection). I've done it before with vanilla classes that I needed a reference to, but my question is: can I use the Activator to get access to a static class?

The part that's tripping me up is that the Activator returns to you a instance of the object, whereas a static class has no instance. Is this possible?

Pottage answered 5/3, 2009 at 13:58 Comment(0)
P
24

You do not need the Activator to call the method. You use MethodInfo.Invoke directly. The first parameter can be left null.

Pecos answered 5/3, 2009 at 14:4 Comment(0)
R
15

GvS is correct - here is an example of the usage:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type type = Type.GetType("Foo");
        MethodInfo info = type.GetMethod("Bar");

        Console.WriteLine(info.Invoke(null, null));
    }
}

static class Foo
{
    public static String Bar() { return "Bar"; }
}
Revival answered 5/3, 2009 at 14:9 Comment(1)
Isn't there any way to do this without using hot strings?Homeomorphism
B
7

One more example using MethodInfo.Invoke

Type myStaticClassType = Type.GetType("MyStaticClassNameSpace",true);
object[] myStaticMethodArguments = {object1,object2...};
MethodInfo myStaticMethodInfo = myStaticClassType.GetMethod("YourMethod");
var myStaticMethodResult = myStaticMethodInfo.Invoke(null,myStaticMethodArguments);
Balzac answered 19/2, 2015 at 16:10 Comment(0)
L
0

It is not that static class has no instance, it's just it doesn't have any public constructors. Activator uses reflection to create instances, and when you use reflection you can call anything you want, even private constructors

Luhe answered 5/3, 2009 at 14:5 Comment(0)
W
0

If what you mean by saying "resources" is in fact resources embedded in the assembly, you can always extract them manually (see Assembly.GetManifestResourceStream()), without using static classes (there will be more problems with those since the only way you can use them is purely with reflection).

Spring.NET has a nice IResource abstraction.

And no, Activator cannot be used to "create" static classes.

Welford answered 5/3, 2009 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.