菜鸟C#成长记——嵌套类
我们都知道,类是有成员的,而类的成员是另一个用户定义的类型也是完全有可能。偶尔的,被包含的类可以为其外层类的服务而存在,因为它不必要向外界暴露。其实,嵌套类就是一个辅助类。这就是嵌套类。
嵌套类的好处是可以对外层类的所有成员进行访问。嵌套类的方法可以访问外层类的私有成员。这里要说明一点:公共的嵌套类可以在外层类的作用域内访问。
using System;
using System.Collections.Generic;
using System.Text;
namespace 嵌套类的使用
{
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public override string ToString()
{
return String.Format("{0}/{1}", numerator, denominator);
}
//嵌套类
internal class FractionArtist
{
public void Draw(Fraction f)
{
Console.WriteLine("Drawing the unmerator:{0}",f .numerator );
Console.WriteLine("Drawing the denominator:{0}", f.denominator);
}
}
}
class Program
{
static void Main(string[] args)
{
Fraction f = new Fraction(3, 4);
Console.WriteLine("f1:{0}",f .ToString ());
//实例化嵌套类
Fraction.FractionArtist fa = new Fraction.FractionArtist();
fa.Draw(f);
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace 嵌套类的使用
{
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public override string ToString()
{
return String.Format("{0}/{1}", numerator, denominator);
}
//嵌套类
internal class FractionArtist
{
public void Draw(Fraction f)
{
Console.WriteLine("Drawing the unmerator:{0}",f .numerator );
Console.WriteLine("Drawing the denominator:{0}", f.denominator);
}
}
}
class Program
{
static void Main(string[] args)
{
Fraction f = new Fraction(3, 4);
Console.WriteLine("f1:{0}",f .ToString ());
//实例化嵌套类
Fraction.FractionArtist fa = new Fraction.FractionArtist();
fa.Draw(f);
Console.ReadLine();
}
}
}
FractionArtist只有一个成员:Draw()方法。它可以自由地访问Fraction的私有成员f .numerator和f.denominator,我们可以将这种情况理解问题成员的作用域!如果不是嵌套类,其他类要访问根本不可能。