Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Store class definition in dictionary, instance later

What I want to do is something like the following (All object class have a common interface):

MyDict.Add("A", MyAObjectClass); // Not an instance
MyDict.Add("B", MyBObjectClass);
MyDict.Add("C", MyCOjbectClass);
String typeIwant = "B"; // Could be passed to a function or something
MyCommonInterface myobject = MyDict[typeIwant]();

How could I program something like this?

The purpose of this is to not have to create instances of every single type I will store in my dictionary (could be quite a bit of them) and instead only instance the one I'm actually going to use.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can store type information with a Type object:

var dict = new Dictionary<String, Type>();

dict.Add("A", typeof(TextBox));
dict.Add("B", typeof(Button));

and create objects from it like this:

object a = Activator.CreateInstance(dict["A"]);

This will only work with types with a parameterless constructor. For instance, new TextBox(). If your types have constructors that take the same arguments, you can add the arguments after dict["A"] or pass an array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...