Lire en anglais

Partager via


Type.GetTypeFromCLSID Méthode

Définition

Obtient le type associé à l'identificateur de classe (CLSID) spécifié.

Surcharges

GetTypeFromCLSID(Guid)

Obtient le type associé à l'identificateur de classe (CLSID) spécifié.

GetTypeFromCLSID(Guid, Boolean)

Obtient le type associé à l'identificateur de classe (CLSID) spécifié, indiquant s'il faut lever une exception en cas d'erreur pendant le chargement du type.

GetTypeFromCLSID(Guid, String)

Obtient le type associé à l'identificateur de classe (CLSID) spécifié à partir du serveur défini.

GetTypeFromCLSID(Guid, String, Boolean)

Obtient le type associé à l'identificateur de classe (CLSID) spécifié à partir du serveur défini, indiquant s'il faut lever une exception en cas d'erreur pendant le chargement du type.

GetTypeFromCLSID(Guid)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Obtient le type associé à l'identificateur de classe (CLSID) spécifié.

C#
public static Type? GetTypeFromCLSID (Guid clsid);
C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static Type? GetTypeFromCLSID (Guid clsid);
C#
public static Type GetTypeFromCLSID (Guid clsid);

Paramètres

clsid
Guid

CLSID du type à obtenir.

Retours

System.__ComObject que le CLSID soit valide ou non.

Attributs

Exemples

L’exemple suivant utilise le CLSID de l’objet Application Microsoft Word pour récupérer un type COM qui représente l’application Microsoft Word. Il instancie ensuite le type en appelant la méthode et le Activator.CreateInstance ferme en appelant la méthode Application.Quit .

C#
using System;
using System.Reflection;
using System.Runtime.InteropServices;

public class Example
{
   private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
   
   public static void Main()
   {
      // Start an instance of the Word application.
      var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID));
      Console.WriteLine("Instantiated Type object from CLSID {0}",
                        WORD_CLSID);
      Object wordObj = Activator.CreateInstance(word);
      Console.WriteLine("Instantiated {0}", 
                        wordObj.GetType().FullName);
      
      // Close Word.
      word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, 
                        wordObj, new object[] { 0, 0, false } );
   }
}
// The example displays the following output:
//    Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
//    Instantiated Microsoft.Office.Interop.Word.ApplicationClass

Remarques

La GetTypeFromCLSID méthode prend en charge l’accès à liaison tardive aux objets COM non managés à partir d’applications .NET Framework lorsque vous connaissez l’identificateur de classe (CLSID) de l’objet COM. L’identificateur de classe pour les classes COM est défini dans la clé HKEY_CLASSES_ROOT\CLSID du Registre. Vous pouvez récupérer la valeur de la IsCOMObject propriété pour déterminer si le type retourné par cette méthode est un objet COM.

Conseil

Vous pouvez appeler la méthode pour l’accès GetTypeFromProgID lié en retard aux objets COM dont vous connaissez l’identificateur programmatique (ProgID).

L’instanciation d’un objet COM non managé à partir de son CLSID est un processus en deux étapes :

  1. Obtenez un Type objet qui représente le__ComObject qui correspond au CLSID en appelant la GetTypeFromCLSID méthode .

  2. Appelez la Activator.CreateInstance(Type) méthode pour instancier l’objet COM.

Consultez l’exemple pour obtenir une illustration.

La GetTypeFromCLSID(Guid) surcharge ignore toute exception qui peut se produire lors de l’instanciation d’un Type objet basé sur l’argument clsid . Notez qu’aucune exception n’est levée si clsid elle n’est pas trouvée dans le Registre.

Notes pour les appelants

Cette méthode est destinée à être utilisée lors de l’utilisation d’objets COM, et non avec des objets .NET Framework. Tous les objets managés, y compris ceux qui sont visibles par COM (c’est-à-dire, leur ComVisibleAttribute attribut est true) ont un GUID qui est retourné par la GUID propriété . Bien que la méthode retourne un Type objet qui correspond au GUID des objets .NET Framework, vous ne pouvez pas utiliser cet Type objet pour créer une instance de type en appelant la CreateInstance(Type) méthode, comme le montre l’exemple suivant.

C#
using System;
using System.Runtime.InteropServices;

[assembly:ComVisible(true)]

// Define two classes, and assign one an explicit GUID.
[GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")]
public class ExplicitGuid
{ }

public class NoExplicitGuid
{ }

public class Example
{
   public static void Main()
   {
      Type explicitType = typeof(ExplicitGuid);
      Guid explicitGuid = explicitType.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        explicitCOM.Name, explicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        explicitType.Name, explicitCOM.Name,
                        explicitType.Equals(explicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(explicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      } 
        
      Type notExplicit = typeof(NoExplicitGuid);
      Guid notExplicitGuid = notExplicit.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        notExplicitCOM.Name, notExplicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        notExplicit.Name, notExplicitCOM.Name,
                        notExplicit.Equals(notExplicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(notExplicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      }   
   }
}
// The example displays the following output:
//       Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4
//       ExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
//       
//       Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb
//       NoExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Au lieu de cela, le GetTypeFromCLSID(Guid, String, Boolean) doit uniquement être utilisé pour récupérer le GUID d’un objet COM non managé, et l’objet résultant Type passé à la CreateInstance(Type) méthode doit représenter un objet COM non managé.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetTypeFromCLSID(Guid, Boolean)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Obtient le type associé à l'identificateur de classe (CLSID) spécifié, indiquant s'il faut lever une exception en cas d'erreur pendant le chargement du type.

C#
public static Type? GetTypeFromCLSID (Guid clsid, bool throwOnError);
C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static Type? GetTypeFromCLSID (Guid clsid, bool throwOnError);
C#
public static Type GetTypeFromCLSID (Guid clsid, bool throwOnError);

Paramètres

clsid
Guid

CLSID du type à obtenir.

throwOnError
Boolean

true pour lever toute exception qui se produit.

- ou -

false pour ignorer toute exception qui se produit.

Retours

System.__ComObject que le CLSID soit valide ou non.

Attributs

Exemples

L’exemple suivant utilise le CLSID de l’objet Application Microsoft Word pour récupérer un type COM qui représente l’application Microsoft Word. Il instancie ensuite le type en appelant la méthode et le Activator.CreateInstance ferme en appelant la méthode Application.Quit . Une exception est levée si une erreur se produit lors du chargement du type.

C#
using System;
using System.Reflection;
using System.Runtime.InteropServices;

public class Example
{
   private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
   
   public static void Main()
   {
      try {
         // Start an instance of the Word application.
         var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), true);
         Console.WriteLine("Instantiated Type object from CLSID {0}",
                           WORD_CLSID);
         Object wordObj = Activator.CreateInstance(word);
         Console.WriteLine("Instantiated {0}", 
                           wordObj.GetType().FullName, WORD_CLSID);
         
         // Close Word.
         word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, 
                           wordObj, new object[] { 0, 0, false } );
      }
      catch (Exception) {
         Console.WriteLine("Unable to instantiate an object for {0}", WORD_CLSID);
      }
   }
}
// The example displays the following output:
//    Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
//    Instantiated Microsoft.Office.Interop.Word.ApplicationClass

Remarques

La GetTypeFromCLSID méthode prend en charge l’accès à liaison tardive aux objets COM non managés à partir d’applications .NET Framework lorsque vous connaissez l’identificateur de classe (CLSID) de l’objet COM. L’identificateur de classe pour les classes COM est défini dans la clé HKEY_CLASSES_ROOT\CLSID du Registre. Vous pouvez récupérer la valeur de la IsCOMObject propriété pour déterminer si le type retourné par cette méthode est un objet COM.

Conseil

Vous pouvez appeler la méthode pour l’accès GetTypeFromProgID lié en retard aux objets COM dont vous connaissez l’identificateur programmatique (ProgID).

L’instanciation d’un objet COM non managé à partir de son CLSID est un processus en deux étapes :

  1. Obtenez un Type objet qui représente le __ComObject qui correspond au CLSID en appelant la GetTypeFromCLSID méthode .

  2. Appelez la Activator.CreateInstance(Type) méthode pour instancier l’objet COM.

Consultez l’exemple pour obtenir une illustration.

Des exceptions telles que OutOfMemoryException seront levées lors de la spécification true pour throwOnError, mais cela n’échouera pas pour les CLSID non enregistrés.

Notes pour les appelants

Cette méthode est destinée à être utilisée lors de l’utilisation d’objets COM, et non avec des objets .NET Framework. Tous les objets managés, y compris ceux qui sont visibles par COM (c’est-à-dire, leur ComVisibleAttribute attribut est true) ont un GUID qui est retourné par la GUID propriété . Bien que la méthode retourne un Type objet qui correspond au GUID des objets .NET Framework, vous ne pouvez pas utiliser cet Type objet pour créer une instance de type en appelant la CreateInstance(Type) méthode, comme le montre l’exemple suivant.

C#
using System;
using System.Runtime.InteropServices;

[assembly:ComVisible(true)]

// Define two classes, and assign one an explicit GUID.
[GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")]
public class ExplicitGuid
{ }

public class NoExplicitGuid
{ }

public class Example
{
   public static void Main()
   {
      Type explicitType = typeof(ExplicitGuid);
      Guid explicitGuid = explicitType.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        explicitCOM.Name, explicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        explicitType.Name, explicitCOM.Name,
                        explicitType.Equals(explicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(explicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      } 
        
      Type notExplicit = typeof(NoExplicitGuid);
      Guid notExplicitGuid = notExplicit.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        notExplicitCOM.Name, notExplicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        notExplicit.Name, notExplicitCOM.Name,
                        notExplicit.Equals(notExplicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(notExplicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      }   
   }
}
// The example displays the following output:
//       Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4
//       ExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
//       
//       Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb
//       NoExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Au lieu de cela, le GetTypeFromCLSID(Guid, String, Boolean) doit uniquement être utilisé pour récupérer le GUID d’un objet COM non managé, et l’objet résultant Type passé à la CreateInstance(Type) méthode doit représenter un objet COM non managé.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetTypeFromCLSID(Guid, String)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Obtient le type associé à l'identificateur de classe (CLSID) spécifié à partir du serveur défini.

C#
public static Type? GetTypeFromCLSID (Guid clsid, string? server);
C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static Type? GetTypeFromCLSID (Guid clsid, string? server);
C#
public static Type GetTypeFromCLSID (Guid clsid, string server);

Paramètres

clsid
Guid

CLSID du type à obtenir.

server
String

Serveur à partir duquel le type doit être chargé. Si le nom de serveur est null, cette méthode revient automatiquement à la machine locale.

Retours

System.__ComObject que le CLSID soit valide ou non.

Attributs

Exemples

L’exemple suivant utilise le CLSID de l’objet Application Microsoft Word pour récupérer un type COM qui représente l’application Microsoft Word à partir d’un serveur nommé computer17.central.contoso.com. Il instancie ensuite le type en appelant la méthode et le Activator.CreateInstance ferme en appelant la méthode Application.Quit .

C#
using System;
using System.Reflection;
using System.Runtime.InteropServices;

public class Example
{
   private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
   
   public static void Main()
   {
      // Start an instance of the Word application.
      var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), "computer17.central.contoso.com");
      Console.WriteLine("Instantiated Type object from CLSID {0}",
                        WORD_CLSID);
      try {
         Object wordObj = Activator.CreateInstance(word);
         Console.WriteLine("Instantiated {0}", 
                           wordObj.GetType().FullName, WORD_CLSID);
            
         // Close Word.
         word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, 
                           wordObj, new object[] { 0, 0, false } );
      }
      catch (COMException) {
         Console.WriteLine("Unable to instantiate object.");   
      }
   }
}
// The example displays the following output:
//    Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
//    Instantiated Microsoft.Office.Interop.Word.ApplicationClass

Remarques

La GetTypeFromCLSID méthode prend en charge l’accès à liaison tardive aux objets COM non managés à partir d’applications .NET Framework lorsque vous connaissez l’identificateur de classe (CLSID) de l’objet COM. L’identificateur de classe pour les classes COM est défini dans la clé HKEY_CLASSES_ROOT\CLSID du Registre. Vous pouvez récupérer la valeur de la IsCOMObject propriété pour déterminer si le type retourné par cette méthode est un objet COM.

Conseil

Vous pouvez appeler la méthode pour l’accès GetTypeFromProgID lié en retard aux objets COM dont vous connaissez l’identificateur programmatique (ProgID).

L’instanciation d’un objet COM non managé à partir de son CLSID est un processus en deux étapes :

  1. Obtenez un Type objet qui représente le __ComObject qui correspond au CLSID en appelant la GetTypeFromCLSID méthode .

  2. Appelez la Activator.CreateInstance(Type) méthode pour instancier l’objet COM.

Notes pour les appelants

Cette méthode est destinée à être utilisée lors de l’utilisation d’objets COM, et non avec des objets .NET Framework. Tous les objets managés, y compris ceux qui sont visibles par COM (c’est-à-dire, leur ComVisibleAttribute attribut est true) ont un GUID qui est retourné par la GUID propriété . Bien que la méthode retourne un Type objet qui correspond au GUID des objets .NET Framework, vous ne pouvez pas utiliser cet Type objet pour créer une instance de type en appelant la CreateInstance(Type) méthode, comme le montre l’exemple suivant.

C#
using System;
using System.Runtime.InteropServices;

[assembly:ComVisible(true)]

// Define two classes, and assign one an explicit GUID.
[GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")]
public class ExplicitGuid
{ }

public class NoExplicitGuid
{ }

public class Example
{
   public static void Main()
   {
      Type explicitType = typeof(ExplicitGuid);
      Guid explicitGuid = explicitType.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        explicitCOM.Name, explicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        explicitType.Name, explicitCOM.Name,
                        explicitType.Equals(explicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(explicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      } 
        
      Type notExplicit = typeof(NoExplicitGuid);
      Guid notExplicitGuid = notExplicit.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        notExplicitCOM.Name, notExplicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        notExplicit.Name, notExplicitCOM.Name,
                        notExplicit.Equals(notExplicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(notExplicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      }   
   }
}
// The example displays the following output:
//       Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4
//       ExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
//       
//       Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb
//       NoExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Au lieu de cela, le GetTypeFromCLSID(Guid, String, Boolean) doit uniquement être utilisé pour récupérer le GUID d’un objet COM non managé, et l’objet résultant Type passé à la CreateInstance(Type) méthode doit représenter un objet COM non managé.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetTypeFromCLSID(Guid, String, Boolean)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Obtient le type associé à l'identificateur de classe (CLSID) spécifié à partir du serveur défini, indiquant s'il faut lever une exception en cas d'erreur pendant le chargement du type.

C#
public static Type? GetTypeFromCLSID (Guid clsid, string? server, bool throwOnError);
C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static Type? GetTypeFromCLSID (Guid clsid, string? server, bool throwOnError);
C#
public static Type GetTypeFromCLSID (Guid clsid, string server, bool throwOnError);

Paramètres

clsid
Guid

CLSID du type à obtenir.

server
String

Serveur à partir duquel le type doit être chargé. Si le nom de serveur est null, cette méthode revient automatiquement à la machine locale.

throwOnError
Boolean

true pour lever toute exception qui se produit.

- ou -

false pour ignorer toute exception qui se produit.

Retours

System.__ComObject que le CLSID soit valide ou non.

Attributs

Exemples

L’exemple suivant utilise le CLSID de l’objet Application Microsoft Word pour récupérer un type COM qui représente l’application Microsoft Word à partir d’un serveur nommé computer17.central.contoso.com. Il instancie ensuite le type en appelant la méthode et le Activator.CreateInstance ferme en appelant la méthode Application.Quit . Une exception est levée si une erreur se produit lors du chargement du type.

C#
using System;
using System.Reflection;
using System.Runtime.InteropServices;

public class Example
{
   private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
   
   public static void Main()
   {
      try {
         // Start an instance of the Word application.
         var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), 
                                          "computer17.central.contoso.com",
                                          true);
         Console.WriteLine("Instantiated Type object from CLSID {0}",
                           WORD_CLSID);
         Object wordObj = Activator.CreateInstance(word);
         Console.WriteLine("Instantiated {0}", 
                           wordObj.GetType().FullName, WORD_CLSID);
            
         // Close Word.
         word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, 
                           wordObj, new object[] { 0, 0, false } );
      }
      // The method can throw any of a variety of exceptions.
      catch (Exception e) {
         Console.WriteLine("{0}: Unable to instantiate an object for {1}", 
                           e.GetType().Name, WORD_CLSID);
      }      
   }
}
// The example displays the following output:
//    Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
//    Instantiated Microsoft.Office.Interop.Word.ApplicationClass

Remarques

La GetTypeFromCLSID méthode prend en charge l’accès à liaison tardive aux objets COM non managés à partir d’applications .NET Framework lorsque vous connaissez l’identificateur de classe (CLSID) de l’objet COM. L’identificateur de classe pour les classes COM est défini dans la clé HKEY_CLASSES_ROOT\CLSID du Registre. Vous pouvez récupérer la valeur de la IsCOMObject propriété pour déterminer si le type retourné par cette méthode est un objet COM.

Conseil

Vous pouvez appeler la méthode pour l’accès GetTypeFromProgID lié en retard aux objets COM dont vous connaissez l’identificateur programmatique (ProgID).

L’instanciation d’un objet COM non managé à partir de son CLSID est un processus en deux étapes :

  1. Obtenez un Type objet qui représente le __ComObject qui correspond au CLSID en appelant la GetTypeFromCLSID méthode .

  2. Appelez la Activator.CreateInstance(Type) méthode pour instancier l’objet COM.

Des exceptions telles que OutOfMemoryException seront levées lors de la spécification true pour throwOnError, mais cela n’échouera pas pour les CLSID non enregistrés.

Notes pour les appelants

Cette méthode est destinée à être utilisée lors de l’utilisation d’objets COM, et non avec des objets .NET Framework. Tous les objets managés, y compris ceux qui sont visibles par COM (c’est-à-dire, leur ComVisibleAttribute attribut est true) ont un GUID qui est retourné par la GUID propriété . Bien que la GetTypeFromCLSID(Guid, String, Boolean) méthode retourne un Type objet qui correspond au GUID d’un objet managé particulier, vous ne pouvez pas utiliser cet Type objet pour créer une instance de type en appelant la CreateInstance(Type) méthode, comme le montre l’exemple suivant.

C#
using System;
using System.Runtime.InteropServices;

[assembly:ComVisible(true)]

// Define two classes, and assign one an explicit GUID.
[GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")]
public class ExplicitGuid
{ }

public class NoExplicitGuid
{ }

public class Example
{
   public static void Main()
   {
      Type explicitType = typeof(ExplicitGuid);
      Guid explicitGuid = explicitType.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        explicitCOM.Name, explicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        explicitType.Name, explicitCOM.Name,
                        explicitType.Equals(explicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(explicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      } 
        
      Type notExplicit = typeof(NoExplicitGuid);
      Guid notExplicitGuid = notExplicit.GUID;
      
      // Get type of ExplicitGuid from its GUID.
      Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
      Console.WriteLine("Created {0} type from CLSID {1}",
                        notExplicitCOM.Name, notExplicitGuid);
                        
      // Compare the two type objects.
      Console.WriteLine("{0} and {1} equal: {2}",
                        notExplicit.Name, notExplicitCOM.Name,
                        notExplicit.Equals(notExplicitCOM));                  
      
      // Instantiate an ExplicitGuid object.
      try {
         Object obj = Activator.CreateInstance(notExplicitCOM);
         Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
      } 
      catch (COMException e) {
         Console.WriteLine("COM Exception:\n{0}\n", e.Message);   
      }   
   }
}
// The example displays the following output:
//       Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4
//       ExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
//       
//       Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb
//       NoExplicitGuid and __ComObject equal: False
//       COM Exception:
//       Retrieving the COM class factory for component with CLSID 
//       {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: 
//       80040154 Class not registered 
//       (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Au lieu de cela, le GetTypeFromCLSID(Guid, String, Boolean) doit uniquement être utilisé pour récupérer le GUID d’un objet COM non managé, et l’objet résultant Type passé à la CreateInstance(Type) méthode doit représenter un objet COM non managé.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1