开发者

In C#, how to create an object given the name of its type? [duplicate]

This question already has answers here: Create an instance of a class from a string (8 answers) 开发者_JAVA百科 Closed 9 years ago.

I know the type of object (let's say IAnimal) I need to instantiate, and the name (lets say Tiger). How do I write the code to instantiate Tiger, given that the variable that knows the object name is a string. I'm likely missing something simple here, but am currently stuck on this.

Update: I meant Class Tiger : IAnimal, changed above to reflect that.


Using the Activator.CreateInstance method

example:

// the string name must be fully qualified for GetType to work
string objName = "TestCreateInstance.MyObject";
IProcess txObject = (IProcess)Activator.CreateInstance(Type.GetType(objName));

or

object o = Activator.CreateInstance("Assem1.dll", "Friendly.Greeting");

See also: Reflection Examples C#


Use reflection to instantiate an object of a class by its type name.

object o = Activator.CreateInstance(Type.GetType("Tiger"));

Note that you cannot instantiate interfaces (judging by your naming), as they are merely a contract that defines what a specific class should implement.


I am not sure I fully understand the question. However, assuming that ITiger is actually a concrete class and not an interface (as the I* would suggest).

You can use reflection to create and instance of a type from a string.

Something like:

ITiger myTiger = Activator.CreateInstance("ITiger") as ITiger;

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Is that what you are asking?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜