用好.NET 的Indexer (索引器)

受到惯性影响,我们常常把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; }
        }

        
///   <summary>
        
///  可以提供类似 Federated PK的功能
        
///   </summary>
        
///   <param name="index"></param>
        
///   <param name="i"></param>
        
///   <returns></returns>
         public   string   this [ string  index,  int  i]
        {
            
get  {  return  index  +  i; }
        }

        
///   <summary>
        
///  已经可以非常类似SQL语句中Where子句的效果
        
///   </summary>
        
///   <param name="predicate"></param>
        
///   <returns></returns>
         public   float   this [Predicate < float >  predicate]
        {
            
get
            {
                
float [] matches  =  Array.FindAll < float > (temps, predicate);

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

                
return  matches[ 0 ];
            }
        }

        
///   <summary>
        
///  已经可以非常类似SQL语句中一组Where子句的效果
        
///   </summary>
        
///   <param name="predicates"></param>
        
///   <returns></returns>
         public   float   this [ params  Predicate < float > [] 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;
                }]);
        }
    }
}

你可能感兴趣的:(index)