说明

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

什么是依赖属性?

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

  1. class MyClass
  2. {
  3. public int MyProperty { get; set; }
  4. }

而依赖属性,是具有注入特征的属性。基本声明步骤如下:

  1. 继承RRQMDependencyObject
  2. 按如下格式生成属性项(propdp代码块可快速实现) ```csharp class MyClass: RRQMDependencyObject { ///

    /// 属性项 /// public int MyProperty {

    1. get { return (int)GetValue(MyPropertyProperty); }
    2. set { SetValue(MyPropertyProperty, value); }

    }

    ///

    /// 依赖项 /// public static readonly DependencyProperty MyPropertyProperty =

    1. DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), 10);

}

  1. <a name="k5TQT"></a>
  2. ## 优缺点
  3. 优点:
  4. 1. 可以不声明在类内部。这意味着可以从外部注入。
  5. 1. 不需要初始赋值,也就意味着创建大量对象时,可以不需要占用太多内存。
  6. 缺点:
  7. 1. 涉及拆装箱操作,对值类型有一定性能影响。
  8. <a name="vinRS"></a>
  9. ## 示例使用
  10. 假设以下情况:<br />对于RRQMSocket的**IClient**接口对象(已经实现IRRQMDependencyObject),希望创建一个int类型的,名为MyProperty的依赖项属性。
  11. 那么,可以用下列代码实现
  12. ```csharp
  13. public static class DependencyExtensions
  14. {
  15. /// <summary>
  16. /// 依赖项
  17. /// </summary>
  18. public static readonly DependencyProperty MyPropertyProperty =
  19. DependencyProperty.Register("MyProperty", typeof(int), typeof(DependencyExtensions), 10);
  20. /// <summary>
  21. /// 设置MyProperty
  22. /// </summary>
  23. /// <typeparam name="TClient"></typeparam>
  24. /// <param name="client"></param>
  25. /// <param name="value"></param>
  26. /// <returns></returns>
  27. public static TClient SetMyProperty<TClient>(this TClient client, int value) where TClient : IClient
  28. {
  29. client.SetValue(MyPropertyProperty, value);
  30. return client;
  31. }
  32. /// <summary>
  33. /// 获取MyProperty
  34. /// </summary>
  35. /// <typeparam name="TClient"></typeparam>
  36. /// <param name="client"></param>
  37. /// <returns></returns>
  38. public static int GetMyProperty<TClient>(this TClient client) where TClient : IClient
  39. {
  40. return client.GetValue<int>(MyPropertyProperty);
  41. }
  42. }

当需要为TcpClient操作属性时,下列操作即可

  1. TcpClient tcpClient = new TcpClient();
  2. tcpClient.SetMyProperty(100);
  3. int MyProperty = tcpClient.GetMyProperty();

当某个属性会被频繁使用时,不建议使用依赖属性,可以通过继承,直接创建常规属性。