包含此页的版本:
不含此页的版本:
住宿访客是在 Properties API 之上构建的算法。
您可以使用访问器向类型添加功能,而无需直接修改。您可以创建高度通用的访客来控制算法本身和访问过程。这与访客模式的经典实现不同,在访客模式中,访问通常发生在已知的提前类型结构上。它支持序列化、类似检查器的 UI 生成等功能。
以下是访客的基本模式。它发生在财产袋和财产配套对象上。
您可以使用以下方法创建访客以获取属性:
Unity.Properties.PropertyVisitor基类。指用PropertyVisitor创建住宿访客举个例子。IPropertyBagVisitor和IPropertyVisitor接口。有关示例,请参阅使用低级API创建住宿访客。第一种方法是最简单的入门方法。但是,要更广泛地自定义属性包和属性的访问行为,请使用第二种方法,它提供了更大的灵活性和性能改进的潜力。
以下示例使用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。这可能会导致首次接受对象访问时执行速度变慢。