Version: 2023.1
언어: 한국어
프로퍼티 백
프로퍼티 경로

프로퍼티 방문자

프로퍼티 방문자는 프로퍼티 API에 빌드된 알고리즘입니다.

개념

방문자를 사용하여 직접 수정하지 않고도 타입에 기능을 추가할 수 있습니다. 매우 일반적인 방문자를 생성하여 알고리즘 자체와 방문 프로세스를 모두 제어할 수 있습니다. 이는 일반적으로 알려진 AOT(ahead-of-time) 타입 구조에서 방문이 발생하는 방문자 패턴의 클래식 구현과는 다릅니다. 직렬화, 인스펙터와 유사한 UI 생성 등의 기능을 사용할 수 있습니다.

다음은 방문자의 기본 패턴입니다. 이는 프로퍼티 백과 프로퍼티 컴패니언 오브젝트에서 발생합니다.

  1. 어느 타입의 인스턴스가 방문자를 수락합니다.
  2. 방문자는 인스턴스의 프로퍼티 백을 방문합니다.
  3. 프로퍼티 백은 프로퍼티를 반복하여 방문자를 수락할 수 있습니다.

프로퍼티 방문자를 생성하여 프로퍼티 가져오기

다음 방법을 통해 방문자를 생성하여 프로퍼티를 가져올 수 있습니다.

첫 번째 방법은 가장 쉬운 시작 방법입니다. 하지만 프로퍼티 백과 프로퍼티에 대한 방문 동작을 보다 광범위하게 커스터마이징하려면 더 큰 유연성과 성능 개선 가능성을 제공하는 두 번째 방법을 사용하십시오.

다음 예시에서는 PropertyVisitor 클래스를 사용하여 특정 속성으로 태그가 지정된 타입의 프로퍼티를 가져오는 간단한 방문자를 생성합니다.

public class BindableAttribute
    : Attribute
{
}

public class GatherBindablePropertiesVisitor
    : PropertyVisitor
{
    public List<PropertyPath> BindableProperties { get; set; }

    protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
    {
        if (property.HasAttribute<BindableAttribute>())
            BindableProperties.Add(PropertyPath.AppendProperty(default, property));
    }
}

다음은 IPropertyBagVisitor 인터페이스를 사용하여 방문자를 생성하는 동등한 예시입니다.

public class BindableAttribute
    : Attribute
{
}

public class GatherBindablePropertiesVisitor
    : IPropertyBagVisitor
{
    public List<PropertyPath> BindableProperties { get; set; }

    void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> propertyBag, ref TContainer container)
    {
        // Loop through the properties of the container object.
        foreach (var property in propertyBag.GetProperties(ref container))
        {
            if (property.HasAttribute<BindableAttribute>())
                BindableProperties.Add(PropertyPath.AppendProperty(default, property));
        }
    }
}

로우레벨 방문자는 프로퍼티 백의 모든 프로퍼티를 반복하여 값을 추출할 필요가 없으므로 성능이 더 뛰어납니다. 로우레벨 방문자를 사용하여 프로퍼티 백에 속하지 않는 프로퍼티를 방문할 수도 있습니다.

성능 고려 사항

프로퍼티 백, 프로퍼티, 방문자는 모두 일반적인 타입을 사용하여 구현되므로 가능한 한 강력한 타입을 유지할 수 있으며 많은 경우 방문 중에 박싱 할당을 피할 수 있습니다. 일반적인 타입 사용의 단점은 JIT 컴파일러가 지정된 메서드를 처음 호출할 때 해당 메서드에 대한 IL을 생성한다는 점입니다. 이로 인해 방문자가 오브젝트를 처음으로 수락할 때 실행 속도가 느려질 수 있습니다.

추가 리소스

프로퍼티 백
프로퍼티 경로