Поделиться через


DefaultEventAttribute Класс

Определение

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

public ref class DefaultEventAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class)]
public sealed class DefaultEventAttribute : Attribute
public sealed class DefaultEventAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class)>]
type DefaultEventAttribute = class
    inherit Attribute
type DefaultEventAttribute = class
    inherit Attribute
Public NotInheritable Class DefaultEventAttribute
Inherits Attribute
Наследование
DefaultEventAttribute
Атрибуты

Примеры

В следующем примере определяется класс коллекции с именем MyCollection. Класс помечается как DefaultEventAttributeCollectionChanged событие по умолчанию.

[DefaultEvent("CollectionChanged")]
public ref class TestCollection: public BaseCollection
{
private:
    CollectionChangeEventHandler^ onCollectionChanged;
    
public:
    event CollectionChangeEventHandler^ CollectionChanged 
    {
    public:
        void add(CollectionChangeEventHandler^ eventHandler)
        { 
            onCollectionChanged += eventHandler; 
        }

    protected:
        void remove(CollectionChangeEventHandler^ eventHandler) 
        { 
            onCollectionChanged -= eventHandler; 
        }
    }
    // Insert additional code.
};
[DefaultEvent("CollectionChanged")]
public class MyCollection : BaseCollection
{
    CollectionChangeEventHandler onCollectionChanged;

    public event CollectionChangeEventHandler CollectionChanged
    {
        add => onCollectionChanged += value;
        remove => onCollectionChanged -= value;
    }
    // Insert additional code.
}
<DefaultEvent("CollectionChanged")> _ 
Public Class MyCollection
    Inherits BaseCollection

    Public Event CollectionChanged (ByVal sender As Object, _
        ByVal e As CollectionChangeEventArgs)
    
    ' Insert additional code.
End Class

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

int main()
{
    // Creates a new collection.
    DefaultEventAttributeExample::TestCollection^ newCollection = 
        gcnew DefaultEventAttributeExample::TestCollection;
    
    // Gets the attributes for the collection.
    AttributeCollection^ attributes = 
        TypeDescriptor::GetAttributes(newCollection);
    
    // Prints the name of the default event by retrieving the 
    // DefaultEventAttribute from the AttributeCollection.
    DefaultEventAttribute^ attribute = (DefaultEventAttribute^)
        attributes[DefaultEventAttribute::typeid];
    Console::WriteLine("The default event is: {0}", attribute->Name);
}
public static int Main()
{
    // Creates a new collection.
    MyCollection myNewCollection = new();

    // Gets the attributes for the collection.
    AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewCollection);

    /* Prints the name of the default event by retrieving the
     * DefaultEventAttribute from the AttributeCollection. */
    DefaultEventAttribute myAttribute =
       (DefaultEventAttribute)attributes[typeof(DefaultEventAttribute)];
    Console.WriteLine("The default event is: " + myAttribute.Name);
    return 0;
}
Public Shared Function Main() As Integer
    ' Creates a new collection.
    Dim myNewCollection As New MyCollection()
    
    ' Gets the attributes for the collection.
    Dim attributes As AttributeCollection = TypeDescriptor.GetAttributes(myNewCollection)
    
    ' Prints the name of the default event by retrieving the
    ' DefaultEventAttribute from the AttributeCollection. 
    Dim myAttribute As DefaultEventAttribute = _
        CType(attributes(GetType(DefaultEventAttribute)), DefaultEventAttribute)
    Console.WriteLine(("The default event is: " & myAttribute.Name))
    Return 0
End Function 'Main

Комментарии

Name Используйте свойство, чтобы получить имя события по умолчанию.

Дополнительные сведения см. в разделе Атрибуты.

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

Имя Описание
DefaultEventAttribute(String)

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

Поля

Имя Описание
Default

Указывает значение по умолчанию для параметра DefaultEventAttribute, которое является null. Это static поле доступно только для чтения.

Свойства

Имя Описание
Name

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

TypeId

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

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

Методы

Имя Описание
Equals(Object)

Возвращает значение, равное ли заданному объекту текущее DefaultEventAttributeзначение.

GetHashCode()

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

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)

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

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