C# notes (2)

一、扩展方法

      有许多方法去扩展一个类,而如果没有源代码,怎么办?此时可以用扩喊方法,它允许改变一个类,但不需要类的源代码。扩展方法是静态方法,是类的一部分,尽管不在类的源代码中。比如,由于某种原因,程序集最初的源代码不能直接修改类TestClass,而又想为其添加一个NewMethod,此时可以创建一个静态类,把要添加的方法添加为静态方法。如:

代码
namespace Sample1
{
    
public class TestClass
    {
        
public int Amount{get;set;}
    }
}

namespace Sample2
{
    
public static class TestClassExtension
    {
        
public static void NewMethod(this TestClass testClass, int amountToAdd)
        {
            testClass.Amount 
+= amountToAdd;
        }
    }
}

  

      下面是使用扩展方法。在主程序中,NewMethod方法看起来是另外一个方法,它没有显示第一个参数,也不能对它进行任何处理:

TestClass instance = new TestClass();
instance.Amount 
= 10;
instance.NewMethod(
20);

Console.WriteLine(instance.Amount);

  

二、C#中struct与class的异同

      1.值类型与引用类型

      结构(struct)是值类型:值类型在堆栈上分配地址,所有的基类型都是结构类型,例如:int   对应System.int32   结构,string 对应 system.string 结构,通过使用结构可以创建更多的值类型。

      类(class)是引用类型:引用类型在堆上分配地址。

      堆栈的执行效率要比堆的执行效率高,可是堆栈的资源有限,不适合处理大的逻辑复杂的对象。因为结构是值类型所以结构之间的赋值可以创建新的结构,而类是引用类型,类之间的赋值只是复制引用。

      虽然结构与类的类型不一样,可是他们的基类型都是对象(object),c#中所有类型的基类型都是object;虽然结构的初始化也使用了 New 操作符可是结构对象依然分配在堆栈上而不是堆上,如果不使用“新建”(new),那么在初始化所有字段之前,字段将保持未赋值状态,且对象不可用。

      2.继承性

      结构(struct)不能从另外一个结构或者类继承,本身也不能被继承,虽然结构没有明确的用sealed声明,可是结构是隐式的sealed。
      类(class)是完全可扩展的,除非显示的声明sealed   否则类可以继承其他类和接口,自身也能被继承。

      3.内部结构

      结构(struct):没有默认的构造函数,但是可以添加构造函数;没有析构函数;没有 abstract 和 sealed(因为不能继承);不能有 protected 修饰符;可以不使用 new 初始化;在结构中初始化实例字段是错误的。
      类(class):有默认的构造函数;有析构函数;可以使用 abstract 和 sealed;有 protected 修饰符;必须使用 new 初始化。
 
三、IEnumerable和IEnumerator接口
      C#中,凡是实现了IEnumerator接口的数据类型都可以用 foreach 语句进行迭代访问。先来看看IEnumerableIEnumerator接口的定义:
代码
public interface IEnumerable
{
      
//IEnumerable只有一个方法,返回可循环访问集合的枚举数。
       IEnumerator GetEnumerator()   ;
}

public interface IEnumerator
{  
      
// 方法      
      //移到集合的下一个元素。如果成功则返回为 true;如果超过集合结尾,则返回false。
      bool MoveNext();     
      // 将集合设置为初始位置,该位置位于集合中第一个元素之前
      void Reset();

      
// 属性:获取集合中的当前元素
      object Current { get; }
}

      如果我们的自定义数据类型派生于这两个接口,并实现接口中的方法,即可用foreach进行迭代。下面是一个示例:

MyTestEnum
struct point
{
    
public int x;
    
public int y;
}

class MyTestEnum : IEnumerable, IEnumerator
{
    
private int index;
    
private point[] points;

    
// Constructor
    public MyTestEnum(int numOfPoints)
    {
        
this.index = -1;
        points 
= new point[numOfPoints];

        
for (int i = 0; i < points.Length; i++)
        {
            points[i].x 
= i;
            points[i].y 
= i * i;
        }
    }
    
// 实现IEnumerable接口的GetEnumerator方法,返回一个IEnumerator
    
// 这里返回我们的自定义类,因为要对这个类的对象进行迭代
    public IEnumerator GetEnumerator()
    {
        
return (IEnumerator)this;
    }
    
// 实现IEnumerator接口的Reset方法
    public void Reset()
    {
        index 
= -1;
    }
    
// 实现IEnumerator接口的Current属性
    public object Current
    {
        
get
        {
            
return points[index];
        }
    }
    
//实现IEnumerator接口的MoveNext方法,用于向前访问集合元素,如果超出集合范围,返回false
    public bool MoveNext()
    {
        index
++;
        
return index < points.Length ? true : false;
    }

}

 

      在程序中可以直接对MyTestEnum对象中的points进行foreach迭代了

      MyTestEnum points = new MyTestEnum(10);

      foreach (point p in points)

            Console.WriteLine(p.x + " " + p.y);

 

      现在使用 yield return 语句,很容易实现允许以不同方式迭代集合的类。类Music可以用默认方式通过GetEnumerator()方法迭代music名,用Reverse()方法逆序迭代名字,用Subset()方法搜集子集:

MusicClass
public class Music
{
    
string[] names = {"Tubular Bells""Hergest Ridge""Ommadawn""Xin Lei"};

    
public IEnumerator GetEnumerator()
    {
        
for (int i = 0; i < 4++i)
        {
            
yield return names[i];
        }
    }

    
public IEnumerable Reverse()
    {
        
for (int i = 3; i >= 0--i)
        {
            
yield return names[i];
        }
    }

    
public IEnumerable Subset(int index, int length)
    {
        
for (int i = index; i < index + length; ++i)
        {
            
yield return names[i];
        }
    }
}

 

      迭代字符串数组的客户代码先使用GetEnumerator()方法,该方法不必再代码中编写,因为这是默认使用的方法。然后逆序迭代,最后将索引和要迭代的元素个数传给Subset()方法,来迭代子集:

代码
Music musicNames = new Music();
foreach (string music in musicNames)
{
    Console.WriteLine(music);
}

Console.WriteLine(
"Reverse");
foreach(string music in musicNames.Reverse())
{
    Console.WriteLine(music);
}

Console.WriteLine(
"Subset");
foreach (string music in musicNames.Subset(2,2))
{
    Console.WriteLine(music);
}

 

      那IEnumerable和IEnumerator有什么区别?

      1、一个Collection要支持foreach方式的遍历,必须实现IEnumerable接口(亦即,必须以某种方式返回IEnumerator object)。
      2、IEnumerator object具体实现了iterator(通过MoveNext(),Reset(),Current)。
      3、从这两个接口的用词选择上,也可以看出其不同:IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumerator object就是一个iterator。
      4、IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接,client可以通过 IEnumerable的GetEnumerator()得到IEnumerator object,在这个意义上,将GetEnumerator()看作IEnumerator object的factory method也未尝不可。

 

Go to my home page for more posts

posted on 2010-01-10 20:54  lantionzy  阅读(389)  评论(0编辑  收藏  举报