Структура маркера WinRT:: static_lifetime (C++/WinRT)

Тип маркера, который передается в реализацию базовой структуры фабрики активации, чтобы включить ее в статическое время существования (для закрепления ). Пример использования типов маркеров см. в разделе типы маркеров.

Синтаксис

struct winrt::static_lifetime

Примеры

Ниже приведен конкретный пример WinRT:: static_lifetime. Если требуется, чтобы фабрика активации для мирунтимекласс была Singleton, закрепите ее следующим образом.

// MyRuntimeclass.h
#pragma once

#include "MyRuntimeClass.g.h"

namespace winrt::MYNAMESPACE::implementation
{
    struct MyRuntimeClass : MyRuntimeClassT<MyRuntimeClass> { ... };
}

namespace winrt::MYNAMESPACE::factory_implementation
{
    struct MyRuntimeClass : MyRuntimeClassT<MyRuntimeClass, implementation::MyRuntimeClass, static_lifetime>
    {
    };
}

Необходимо реализовать статические события для объекта фабрики активации с помощью маркера WinRT:: static_lifetime . Закрепите фабрику, чтобы убедиться, что ее время существования стабильно, так как обработчики событий добавляются и удаляются. Все это можно сделать в заголовке, например в следующем примере.

Примечание

Новый проект/WinRT C++ (из шаблона проекта) будет использовать оптимизацию компонентов по умолчанию. Если оптимизация компонентов не используется, можно опустить указанную часть списка.

// MyRuntimeClass.h
#pragma once

#include "MyRuntimeClass.g.h"

// Forward-declare the instance class.
namespace winrt::Component::implementation
{
    struct MyRuntimeClass;
}

// Then define the activation factory class before the instance class.
namespace winrt::Component::factory_implementation
{
    struct MyRuntimeClass : MyRuntimeClassT<MyRuntimeClass, implementation::MyRuntimeClass, static_lifetime>
    {
        winrt::event_token MyRuntimeClassEvent(Windows::Foundation::EventHandler<int32_t> const& handler)
        {
            return m_static.add(handler);
        }

        void MyRuntimeClassEvent(winrt::event_token const& cookie)
        {
            m_static.remove(cookie);
        }

        void RaiseMyRuntimeClassStaticEvent(int32_t value)
        {
            m_static(nullptr, value);
        }

        event<Windows::Foundation::EventHandler<int32_t>> m_static;
    };
}

namespace winrt::Component::implementation
{
    struct MyRuntimeClass
    {
        MyRuntimeClass() = delete;

        // If you're not using component optimizations, then you can omit these next three methods.

        // Component optimizations means that you have to implement any statics on the instance class,
        // and have those forward to the activation factory. You will see build errors if you don't do this.

        static winrt::event_token MyRuntimeClassStaticEvent(Windows::Foundation::EventHandler<int32_t> const& handler)
        {
            return make_self<factory_implementation::MyRuntimeClass>()->MyRuntimeClassStaticEvent(handler);
        }

        static void MyRuntimeClassStaticEvent(winrt::event_token const& cookie)
        {
            return make_self<factory_implementation::MyRuntimeClass>()->MyRuntimeClassStaticEvent(cookie);
        }

        static void RaiseMyRuntimeClassStaticEvent(int32_t value)
        {
            return make_self<factory_implementation::MyRuntimeClass>()->RaiseMyRuntimeClassStaticEvent(value);
        }
    };
}

Требования

минимальный поддерживаемый пакет SDK: Windows SDK версии 10.0.17763.0 (Windows 10, версия 1809)

Пространство имен: WinRT

Заголовок: % Виндовссдкдир% include < WindowsTargetPlatformVersion > \кппвинрт\винрт\басе.х (включен по умолчанию)

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