广州网站建设加q.479185700,wordpress ios,新闻头条最新,网站开发 旅游目录一、为什么要扩展属性二、如何做#xff1f;一、为什么要扩展属性
属性是一个类的特征#xff0c;随着开发的不断升级#xff0c;这种特征可能在一直变化#xff0c;有时候为了向下兼容#xff0c;一般属性的数量都是直接递增的。
例如#xff1a;一个Person类一、为什么要扩展属性
属性是一个类的特征随着开发的不断升级这种特征可能在一直变化有时候为了向下兼容一般属性的数量都是直接递增的。
例如一个Person类他在项目初期只有一个属性Age可随着项目升级可能需要NameAddress甚至Price。
public class Person
{/// summary/// 年龄/// /summarypublic int Age { get; set; }//常规属性
}那么常规做法就是继承然后在子类添加属性。亦或者修改源码重新编译。
无论哪一种都有很大的麻烦事。
继承会让显式的Person类无法使用声明到子类的属性到时候必须进行强制转换而一旦继承分支多起来的话将非常糟糕。
而重新编译带来的问题就更大了总不能把属性都声明在父类吧。何况还有dll版本依赖问题同事推脱问题巴拉巴拉。
二、如何做
我们可以在一开始就将Person类按如下声明。继承DependencyObject。这里需要你先安装TouchSocket的库。
public class Person : DependencyObject
{/// summary/// 年龄/// /summarypublic int Age { get; set; }//常规属性
}然后就Ok了。当后续你需要什么属性的时候自己声明扩展即可。
这样你就可以随意的往Person类中添加属性了。
public static class DependencyExtensions
{/// summary/// 依赖项/// /summarypublic static readonly DependencyPropertyint MyPropertyProperty2 DependencyPropertyint.Register(MyProperty2, typeof(DependencyExtensions), 10);/// summary/// 设置MyProperty2/// /summary/// typeparam nameTClient/typeparam/// param nameclient/param/// param namevalue/param/// returns/returnspublic static TClient SetMyProperty2TClient(this TClient client, int value) where TClient : IDependencyObject{client.SetValue(MyPropertyProperty2, value);return client;}/// summary/// 获取MyProperty2/// /summary/// typeparam nameTClient/typeparam/// param nameclient/param/// returns/returnspublic static int GetMyProperty2TClient(this TClient client) where TClient : IDependencyObject{return client.GetValue(MyPropertyProperty2);}
}使用
Person person new Person();
person.SetMyProperty2(2);//扩展属性必须通过扩展方法
int valueperson.GetMyProperty2();完工。
具体的使用细节可看TouchSocket依赖属性