菜鸟C#成长记——嵌套类

    我们都知道,类是有成员的,而类的成员是另一个用户定义的类型也是完全有可能。偶尔的,被包含的类可以为其外层类的服务而存在,因为它不必要向外界暴露。其实,嵌套类就是一个辅助类。这就是嵌套类。
   
嵌套类的好处是可以对外层类的所有成员进行访问。嵌套类的方法可以访问外层类的私有成员。这里要说明一点:公共的嵌套类可以在外层类的作用域内访问。
   

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

namespace  嵌套类的使用
ExpandedBlockStart.gifContractedBlock.gif
{
    
public class Fraction
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
private int numerator;
        
private int denominator;
        
public Fraction(int numerator, int denominator)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.numerator = numerator;
            
this.denominator = denominator;
        }

        
public override string ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return String.Format("{0}/{1}", numerator, denominator);
        }

        
//嵌套类
        internal class FractionArtist
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
public void Draw(Fraction f)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Console.WriteLine(
"Drawing the unmerator:{0}",f .numerator );
                Console.WriteLine(
"Drawing the denominator:{0}", f.denominator);
            }

        }

    }


    
class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Fraction f 
= new Fraction(34);
            Console.WriteLine(
"f1:{0}",f .ToString ());
            
//实例化嵌套类
            Fraction.FractionArtist fa = new Fraction.FractionArtist();
            fa.Draw(f);
            Console.ReadLine();
        }

    }

}

 

    FractionArtist只有一个成员:Draw()方法。它可以自由地访问Fraction的私有成员f .numeratorf.denominator,我们可以将这种情况理解问题成员的作用域!如果不是嵌套类,其他类要访问根本不可能。

转载于:https://www.cnblogs.com/gishuazi/archive/2008/10/14/1310911.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值