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
320 views
in Technique[技术] by (71.8m points)

c# - 如何从类型创建新的对象实例(How to create a new object instance from a Type)

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type .

(在编译时可能并不总是知道对象的Type ,但可能需要创建Type的实例。)

How do you get a new object instance from a Type ?

(如何从Type获取新的对象实例?)

  ask by tags2k translate from so

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

1 Answer

0 votes
by (71.8m points)

The Activator class within the root System namespace is pretty powerful.

(根System命名空间中的Activator类非常强大。)

There are a lot of overloads for passing parameters to the constructor and such.

(将参数传递给构造函数等有很多重载。)

Check out the documentation at:

(在以下位置查看文档:)

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

(http://msdn.microsoft.com/zh-CN/library/system.activator.createinstance.aspx)

or (new path)

(或(新路径))

https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

(https://docs.microsoft.com/zh-cn/dotnet/api/system.activator.createinstance)

Here are some simple examples:

(以下是一些简单的示例:)

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");

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

...