Megosztás a következőn keresztül:


Visual Basic Concepts

How Object Creation Works in Visual Basic Components

In certain circumstances, the mechanism you use to create objects — that is, CreateObject, the New operator, or a variable declared As New — can have subtle effects on object creation. These effects depend on whether or not Visual Basic uses the object creation services provided by the Component Object Model (COM).

When you create objects from classes that are provided by other components, Visual Basic always uses COM object creation services. As a result, when you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function.

The CreateObject function always uses COM object creation services, whether you use it to create externally provided objects or to create instances of classes that are part of your project. So for CreateObject, there's no difference between external and internal object creation.

However, when you use the New operator (or a variable declared As New) to create an instance of a class that's part of your project, Visual Basic uses a very efficient private implementation of COM object creation.

In other words, Visual Basic uses the same mechanism for all object creation except creating objects with New or As New from classes in your project. This is summarized in the following table.

Object created from Using CreateObject Using New, As New
A class provided by another component COM object creation services COM object creation services
A class that’s part of your project COM object creation services Visual Basic private object creation

Note   The CreateObject function cannot be used on classes whose Instancing property is Private or PublicNotCreatable. The New operator can be used on any class.

The following are specific examples of the subtle differences that can arise depending on how you create objects from classes that are part of your project:

  • If you use the New operator to create an instance of a SingleUse class, the object will be created in your current program instance — as if its Instancing property were MultiUse. Using CreateObject will start another instance of your component. (See "Scalability Through Multiple Processes: SingleUse Objects.")

  • In a multithreaded out-of-process component with thread-per-object or round-robin threading, an instance of any of your project's externally creatable classes created with the New operator will share the thread of the object that executed New — while one created using CreateObject will be on another thread.

  • In a component designed for use with Microsoft Transaction Server, an instance of any of your project's externally creatable classes created with the New operator will be unknown to Microsoft Transaction Server. Objects that will be used with Microsoft Transaction Server must be created using CreateObject.