Skip to main content

依赖属性

一、说明

用过WPF的小伙伴一定对依赖属性不陌生。所以TouchSocket模仿其结构,创建了适用于网络框架的依赖属性。

二、什么是依赖属性?

我们知道常规属性,就是拥有get,set访问器的字段,叫做属性。

class MyClass
{
public int MyProperty { get; set; }
}

而依赖属性,则是具有注入特征的属性。它可以像普通属性一样,声明在类内部(示例1)。也可以声明在任何地方(示例2)。

【示例1】

  1. 继承DependencyObject
  2. 按如下格式生成属性项(propdp代码块可快速实现)
class MyClass: DependencyObject
{
/// <summary>
/// 属性项
/// </summary>
public int MyProperty
{
get { return GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}

/// <summary>
/// 依赖项
/// </summary>
public static readonly DependencyProperty<int> MyPropertyProperty =
DependencyProperty<int>.Register("MyProperty", typeof(MyClass), 10);

}

【示例2】 假设以下情况: 对于TouchSocket的IClient接口对象(已经实现IDependencyObject),希望创建一个int类型的,名为MyProperty的依赖项属性。

那么,可以用下列代码实现

public static class DependencyExtensions
{
/// <summary>
/// 依赖项
/// </summary>
public static readonly DependencyProperty<int> MyPropertyProperty =
DependencyProperty<int>.Register("MyProperty", typeof(MyClass), 10);

/// <summary>
/// 设置MyProperty
/// </summary>
/// <typeparam name="TClient"></typeparam>
/// <param name="client"></param>
/// <param name="value"></param>
/// <returns></returns>
public static TClient SetMyProperty<TClient>(this TClient client, int value) where TClient : IClient
{
client.SetValue(MyPropertyProperty, value);
return client;
}

/// <summary>
/// 获取MyProperty
/// </summary>
/// <typeparam name="TClient"></typeparam>
/// <param name="client"></param>
/// <returns></returns>
public static int GetMyProperty<TClient>(this TClient client) where TClient : IClient
{
return client.GetValue(MyPropertyProperty);
}
}
TcpClient tcpClient = new TcpClient();
tcpClient.SetMyProperty(100);
int MyProperty = tcpClient.GetMyProperty();

三、优缺点

优点:

  1. 可以不声明在类内部。这意味着可以从外部注入。
  2. 不需要初始赋值,也就意味着创建大量对象时,可以不需要占用太多内存。

缺点:

  1. 对于值类型,涉及拆装箱操作,对性能有一定性能影响(不是几百万操作,可以忽略)。
注意

当一个属性被频繁(千万级别)使用时,不建议使用依赖属性。