创造自己的群集类型----之----扩展预定义群集类型属性
通过继承FameWork为我们定义好的群集对象,并对其做扩展处理,可以达到我们想要的结果,本例以ArrayList群集为例,在ArrayList中添加最长/最短元素属性。
注:本例仅作为创建自己群集的方法思路,请勿硬套实际业务或项目。
public class MyStringCollection: ArrayList
{
/// <summary>
/// 获取ArrayList中的最长元素
/// </summary>
private string _longestString;
public string LongestString
{
get
{
return _longestString;
}
set
{
_longestString = value;
}
}
/// <summary>
/// 获取ArrayList中的最短元素
/// </summary>
private string _shortestString;
public string ShortestString
{
get
{
return _shortestString;
}
set
{
_shortestString = value;
}
}
/// <summary>
/// 重写父类方法,为属性赋值
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override int Add(object value)
{
base.Add(value);
if (LongestString == null)
{
LongestString = value.ToString();
}
//最长元素
foreach (var v in base.ToArray())
{
if (v.ToString().Length > LongestString.Length)
{
LongestString = v.ToString();
}
}
//最短元素
foreach (var v in base.ToArray())
{
if (v.ToString().Length < LongestString.Length)
{
LongestString = v.ToString();
}
}
return base.Add(value);
}
}
调用:
protected void Page_Load(object sender, EventArgs e)
{
string longLen = string.Empty;
string shortLen = string.Empty;
MyStringCollection myCollection = new MyStringCollection() { "ddds1", "sdfffffffs2", "sasa", "gggggggggggggg444444444g" };
longLen = dm.LongestString;
shortLen = dm.ShortestString;
HttpContext.Current.Response.Write(string.Format("集合中最长字符串:{0}!", longLen ));
HttpContext.Current.Response.Write(string.Format("集合中最短字符串:{0}!", shortLen ));
}
页面显示:
集合中最长字符串:gggggggggggggg444444444g!
集合中最短字符串:sasa!