I have a lot of classes and want to create som开发者_StackOverflow中文版e kind of 'directory'.
So that I can create menus automatically.
Clicking a menu-item would then create an instance of the class and shows the window.
What I want for this is an array of System.Type where I can stuff in all the classes without instantiating them.
Though from my test and (unsuccessful) googling, this doesn't seem possible.
Any ideas?
Does this work for you to create a simple mapping? ArrayList isn't generic, but you could make a custom object to stuff in there instead.
var mapper = new System.Collections.Generic.Dictionary<string, System.Type>();
mapper.Add("show-about-box", typeof(MyApp.Forms.AboutBox));
Then you can use refleciton to create an instance of the class, using code like this:
// Create an instance using [Activator.CreateInstance][1].
System.Type toCreate = mapper["show-about-box"];
Object o = Activator.CreateInstance(toCreate);
// Or, using try-get to be safer
System.Type toCreate = null;
if ( mapper.TryGetValue("show-about-box", out toCreate) ) {
Object o = Activator.CreateInstance(toCreate);
}
Yes it can be done, if I understand you correctly. Have a look at the classes in the System.Reflection namespace, starting with the Assembly class and its GetExportedTypes method. This gives you an array of publically declared System.Type objects from the specified assembly - http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx
精彩评论