简体   繁体   中英

Array/List/Directory of System.Type

I have a lot of classes and want to create some 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?

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM