Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator and static classes

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?

like image 260
japollock Avatar asked Mar 05 '09 13:03

japollock


People also ask

What is a static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

What is the difference between static and class?

The difference between the Class method and the static method is: A class method takes cls as the first parameter while a static method needs no specific parameters. A class method can access or modify the class state while a static method can't access or modify it.

What are static classes used for?

Static classes are used as containers for static members. Static methods and static properties are the most-used members of a static class. All static members are called directly using the class name. Static methods do a specific job and are called directly using a type name, rather than the instance of a type.

What is activator class in C#?

Activator Class in . NET 4.0. Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. ActivatorClassSample.rar. Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects.


1 Answers

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);
like image 95
andre Avatar answered Sep 24 '22 00:09

andre