首页  ·  知识 ·  云计算
何用好.NET的Indexer
佚名  http://dotnet.csdn.net/  综合  编辑:dezai  图片来源:网络
受到惯性影响,我们常常把indexer作为一个仅仅按照编号反馈结果的入口。但就如SQL 中的where, 我们其实可以做很多。using System; using Syst
受到惯性影响,我们常常把indexer作为一个仅仅按照编号反馈结果的入口。
但就如SQL 中的where, 我们其实可以做很多。

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
class C
{
float[] temps = new float[10] {
56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F };

public float this[int index]
{
get { return temps[index]; }
set { temps[index] = value; }
}

public string this[string index]
{
get { return index; }
}

///
/// 可以提供类似 Federated PK的功能
///

///
///
///
public string this[string index, int i]
{
get { return index + i; }
}

///
/// 已经可以非常类似SQL语句中Where子句的效果
///

///
///
public float this[Predicate predicate]
{
get
{
float[] matches = Array.FindAll(temps, predicate);

#region 输出中间结果
string[] info = Array.ConvertAll(
matches,
delegate(float f)
{
return Convert.ToString(f);
}
);
Console.WriteLine(string.Join(",", info));
#endregion

return matches[0];
}
}

///
/// 已经可以非常类似SQL语句中一组Where子句的效果
///

///
///
public float this[params Predicate[] predicates]
{
get
{
// 具体实现可以参考上面的例子,基本上和我们写SQL的Where类似
// 具体实现略过
return -1;
}
}

}

class Program
{
static void Main(string[] args)
{
C c = new C();
Console.WriteLine(c[4]);
Console.WriteLine(c["Second"]);
Console.WriteLine(c["Second", 2]);
Console.WriteLine(
c[
delegate(float f)
{
return f > 62F;
}]);
}
}
}

来自于博客园 作者:阿飞 本文作者:佚名 来源:http://dotnet.csdn.net/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读