ComImportAttribute Класс

Определение

Указывает, что тип с атрибутом был ранее определен в модели COM.

public ref class ComImportAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)]
public sealed class ComImportAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ComImportAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)>]
type ComImportAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ComImportAttribute = class
    inherit Attribute
Public NotInheritable Class ComImportAttribute
Inherits Attribute
Наследование
ComImportAttribute
Атрибуты

Примеры

В следующем примере показано, как применить объявление управляемого ComImportAttribute интерфейса. Этот атрибут применяется только при создании сборки взаимодействия вручную в исходном коде и требуется имитировать метаданные, созданные Tlbimp.exe.

using namespace System;
using namespace System::Runtime::InteropServices;

// If you do not have a type library for an interface
// you can redeclare it using ComImportAttribute.
// This is how the interface would look in an idl file.
//[
//object,
//uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
//dual, helpstring("IMyStorage Interface"),
//pointer_default(unique)
//]
//interface IMyStorage : IDispatch
//{
// [id(1)]
// HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
// [id(2)]
// HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
// [id(3)]
// HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
// [id(4), propget]
// HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
//};
// This is the managed declaration.

[ComImport]
[Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")]
interface class IMyStorage
{
   [DispId(1)]
   Object^ GetItem( [In,MarshalAs(UnmanagedType::BStr)]String^ bstrName );

   //[return : MarshalAs(UnmanagedType::Interface)]

   [DispId(2)]
   void GetItems( [In,MarshalAs(UnmanagedType::BStr)]String^ bstrLocation, [Out,MarshalAs(UnmanagedType::SafeArray,
   SafeArraySubType=VarEnum::VT_VARIANT)]array<Object^>^Items );

   [DispId(3)]
   void GetItemDescriptions( [In]String^ bstrLocation, [In,Out,MarshalAs(UnmanagedType::SafeArray)]array<Object^>^varDescriptions );

   property bool IsEmpty 
   {
      [DispId(4)]
      [returnvalue:MarshalAs(UnmanagedType::VariantBool)]
      bool get();
   }
};
using System;
using System.Runtime.InteropServices;

namespace MyModule
{
    // If you do not have a type library for an interface
    // you can redeclare it using ComImportAttribute.

    // This is how the interface would look in an idl file.

    //[
    //object,
    //uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
    //dual,	helpstring("IMyStorage Interface"),
    //pointer_default(unique)
    //]
    //interface IMyStorage : IDispatch
    //{
    //	[id(1)]
    //	HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
    //	[id(2)]
    //	HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
    //	[id(3)]
    //	HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
    //	[id(4), propget]
    //	HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
    //};

    // This is the managed declaration.

    [ComImport]
    [Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")]
    public interface IMyStorage
    {
        [DispId(1)]
        [return : MarshalAs( UnmanagedType.Interface )]
        Object GetItem( [In, MarshalAs( UnmanagedType.BStr )] String bstrName );

        [DispId(2)]
        void GetItems( [In, MarshalAs( UnmanagedType.BStr )] String bstrLocation,
            [Out, MarshalAs( UnmanagedType.SafeArray,
                      SafeArraySubType = VarEnum.VT_VARIANT )] out Object[] Items );

        [DispId(3)]
        void GetItemDescriptions( [In] String bstrLocation,
            [In, Out, MarshalAs( UnmanagedType.SafeArray )] ref Object[] varDescriptions );

        bool IsEmpty
        {
            [DispId(4)]
            [return : MarshalAs( UnmanagedType.VariantBool )]
            get;
        }
    }
}
Imports System.Runtime.InteropServices

Module MyModule
    ' If you do not have a type library for an interface
    ' you can redeclare it using ComImportAttribute.

    ' This is how the interface would look in an idl file.

    '[
    'object,
    'uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"),
    'dual,	helpstring("IMyStorage Interface"),
    'pointer_default(unique)
    ']
    'interface IMyStorage : IDispatch
    '{
    '	[id(1)]
    '	HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem);
    '	[id(2)]
    '	HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems);
    '	[id(3)]
    '	HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems);
    '	[id(4), propget]
    '	HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty);
    '};

    ' This is the managed declaration.

    <ComImport(), Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")> _
    Public Interface IMyStorage
        <DispId(1)> _
        Function GetItem(<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByVal bstrName As String) _
           As <MarshalAs(UnmanagedType.Interface)> Object

        <DispId(2)> _
        Function GetItems(<InAttribute(), MarshalAs(UnmanagedType.BStr)> ByVal bstrLocation As String, _
           <OutAttribute(), MarshalAs(UnmanagedType.SafeArray, SafeArraySubType := VarEnum.VT_VARIANT)> _
                                      ByVal Items() As Object)

        <DispId(3)> _
        Function GetItemDescriptions(<InAttribute()> ByVal bstrLocation As String, _
           <InAttribute(), OutAttribute(), _
                      MarshalAs(UnmanagedType.SafeArray)> ByRef varDescriptions() As Object)

        <DispId(4)> _
        ReadOnly Property IsEmpty(<MarshalAs(UnmanagedType.VariantBool)> ByVal bEmpty As Boolean)

    End Interface
End Module

Комментарии

Этот атрибут можно применить к классам или интерфейсам, хотя Tlbimp.exe (средство импорта библиотек типов) обычно применяет его при импорте библиотеки типов.

ComImportAttribute — это псевдопользовательский атрибут, указывающий, что тип был определен в ранее опубликованной библиотеке типов. Среда CLR обрабатывает эти типы по-разному при активации, экспорте, принудительном выполнении и т. д.

Примечание

Все базовые COM-типы, наследуемые управляемым объектом, должны агрегировать FTM. Типы COM, которые не объединяют FTM, не могут наследоваться управляемыми объектами.

Конструкторы

ComImportAttribute()

Инициализирует новый экземпляр класса ComImportAttribute.

Свойства

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

Применяется к

См. также раздел