C# 如何实现对“属性”的扩展

一、为什么要扩展属性

属性是一个类的特征,随着开发的不断升级,这种特征可能在一直变化,有时候为了向下兼容,一般属性的数量都是直接递增的。

例如:一个Person类,他在项目初期,只有一个属性Age,可随着项目升级,可能需要Name,Address,甚至Price。

public class Person
{
    /// <summary>
    /// 年龄
    /// </summary>
    public int Age { get; set; }//常规属性
}

那么常规做法就是继承,然后在子类添加属性。亦或者修改源码,重新编译。

无论哪一种都有很大的麻烦事。

继承,会让显式的Person类无法使用声明到子类的属性,到时候必须进行强制转换,而一旦继承分支多起来的话,将非常糟糕。

而重新编译,带来的问题就更大了,总不能把属性都声明在父类吧。何况还有dll版本依赖问题,同事推脱问题,巴拉巴拉。

二、如何做?

我们可以在一开始,就将Person类按如下声明。继承DependencyObject。这里需要你先安装TouchSocket的库。

public class Person : DependencyObject
{
    /// <summary>
    /// 年龄
    /// </summary>
    public int Age { get; set; }//常规属性
}

然后,就Ok了。当后续你需要什么属性的时候,自己声明扩展即可。

这样,你就可以随意的往Person类中添加属性了。

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

    /// <summary>
    /// 设置MyProperty2
    /// </summary>
    /// <typeparam name="TClient"></typeparam>
    /// <param name="client"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static TClient SetMyProperty2<TClient>(this TClient client, int value) where TClient : IDependencyObject
    {
        client.SetValue(MyPropertyProperty2, value);
        return client;
    }

    /// <summary>
    /// 获取MyProperty2
    /// </summary>
    /// <typeparam name="TClient"></typeparam>
    /// <param name="client"></param>
    /// <returns></returns>
    public static int GetMyProperty2<TClient>(this TClient client) where TClient : IDependencyObject
    {
        return client.GetValue(MyPropertyProperty2);
    }
}

使用

Person person =new Person();
person.SetMyProperty2(2);//扩展属性必须通过扩展方法
int value=person.GetMyProperty2();

完工。

具体的使用细节可看TouchSocket依赖属性

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若汝棋茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值