Reputation: 6771
I have a static class like this:
public static class MyApp
{
public static volatile MultiThreadLogger Logger = new MultiThreadLogger();
}
And a string like this:
"MyApp.Logger"
How can I get the object reference just with knowing the string? The string can be different like "MyOtherNamespace.Subnamespace.StaticObjA.MemberIwantToAccess"
and I don't want to create a new instance, I want to access the static instance - just by the string.
Possible?
Upvotes: 1
Views: 5824
Reputation: 11294
Type t = Type.GetType("MyApp");
PropertyInfo p = t.GetProperty("Logger", Reflection.BindingFlags.Public | Reflection.BindingFlags.Static | Reflection.BindingFlags.FlattenHierarchy);
return p.GetValue(null, null);
http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
How to get a Static property with Reflection
Upvotes: 3
Reputation: 14386
Are you looking for a particular class? In that case, you can add an attribute then iterate the defined classes in an assemlby using reflection, MEF or something similar until you find the right class.
If you are looking for an object (an instance of the class), you will need to "register" it in a factory of some kind, possibly a static Dictionary, then load it from there.
A better solution is to consider IoC containers (http://en.wikipedia.org/wiki/Inversion_of_control). IoC containers will handle the lifetime management and return different versions for testing or different parts of the app. A good explanation of them can be found at http://weblogs.asp.net/sfeldman/archive/2008/02/14/understanding-ioc-container.aspx and a list of then at http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx.
Upvotes: 0
Reputation: 116138
public class ClassFactory
{
static Dictionary<string, object> _Instances;
public static object Get(string type)
{
lock (_Instances)
{
object inst;
if (_Instances.TryGetValue(type, out inst)) return inst;
inst = Activator.CreateInstance(Type.GetType(type));
_Instances.Add(type, inst);
return inst;
}
}
}
Upvotes: 2