说明
用过WPF的小伙伴一定对依赖属性不陌生。所以RRQM模仿其结构,创建了适用于网络框架的依赖属性。
什么是依赖属性?
我们知道常规属性,就是拥有get,set访问器的字段,叫做属性。
class MyClass
{
public int MyProperty { get; set; }
}
而依赖属性,是具有注入特征的属性。基本声明步骤如下:
- 继承RRQMDependencyObject
按如下格式生成属性项(propdp代码块可快速实现) ```csharp class MyClass: RRQMDependencyObject { ///
/// 属性项 /// public int MyProperty {get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
///
/// 依赖项 /// public static readonly DependencyProperty MyPropertyProperty =DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), 10);
}
<a name="k5TQT"></a>
## 优缺点
优点:
1. 可以不声明在类内部。这意味着可以从外部注入。
1. 不需要初始赋值,也就意味着创建大量对象时,可以不需要占用太多内存。
缺点:
1. 涉及拆装箱操作,对值类型有一定性能影响。
<a name="vinRS"></a>
## 示例使用
假设以下情况:<br />对于RRQMSocket的**IClient**接口对象(已经实现IRRQMDependencyObject),希望创建一个int类型的,名为MyProperty的依赖项属性。
那么,可以用下列代码实现
```csharp
public static class DependencyExtensions
{
/// <summary>
/// 依赖项
/// </summary>
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(DependencyExtensions), 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<int>(MyPropertyProperty);
}
}
当需要为TcpClient操作属性时,下列操作即可
TcpClient tcpClient = new TcpClient();
tcpClient.SetMyProperty(100);
int MyProperty = tcpClient.GetMyProperty();
当某个属性会被频繁使用时,不建议使用依赖属性,可以通过继承,直接创建常规属性。