李建忠老师在《Effective C#》 翻译札记一文中提到,可以使用虚属性、或者抽象属性是我们使用属性而不是把field直接暴露的最大的优点之一.虚属性和抽象属性与虚方法和抽象方法的实现没有区别.下面是一个具体的虚属性的实现代码.是用snippet Compiler写的.

using System;
using System.Collections.Generic;

public class Base
{
    
public virtual int Count
    
{
    
get{return 1;}
    }

    
public int Compute()
    
{
        
return Count;
    }

}

public class Derived:Base
{
public override int Count
    
{
    
get {return 5;}
    }

}



public class MyClass
{
    
public static void Main()
    
{
        Derived b = new Derived();
        WL(
"Compute is {0}\n",b.Compute());
        RL();
    }

    
    
Helper methods
}

抽象属性的实现与上类似,具体实现如下:

public abstract class Base
{
    
public abstract int Count
    
{
    
get;
    }

    
public int Compute()
    
{
        
return Count;
    }

}

public class Derived:Base
{
    
public override int  Count
    
{
    
get {return 5;}
    }

}
posted on 2006-10-30 10:19  cinger  阅读(4871)  评论(3编辑  收藏  举报