以前学过C和VB,现在正在着手学C#。有个问题搞不明白,我按一本书上讲的内容自己做了一个例子,代码在下面。为什么我把基类和派生类的定义放在main函数里,C#就会报错?using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
    class Program
    {            public class animal 
            {
                public animal ()
                {
                    Console.WriteLine("Constructing Animal!");
                }
            }            public class elephant : animal 
            {
                public elephant ()
                {
                    Console.WriteLine("Constructing Elephant!");
                }
            }
        static void Main(string[] args)
        {
            elephant e = new elephant();
        }
    }
}

解决方案 »

  1.   

    内部类我很少用,很少这么写,如果要写得话,也不要在里面写继承,可以参看一下,自动生成的模式化DataSet类,里面定义层次这些很多。一般来说一个类对应一个文件,除非是内部类,或类太小了,而且相关性又高,才可以考虑将它们写到一个文件中。更不要随便把类包含在其它类中,这样的设计完全无法被接受的。既然学习C#你就要注意“设计”比如封装什么的,不要一上来就象结构化编程那样把程序的结构搞得复杂化了。
      

  2.   

    using System;
    using System.Text;namespace DataGrid
    {
    /// <summary>
    /// Program 的摘要说明。
    /// </summary>
    public class Program
    {
    class a
    { public class animal 
    {
    public animal ()
    {
    Console.WriteLine("Constructing Animal!");
    }
    } public class elephant : animal 
    {
    public elephant ()
    {
    Console.WriteLine("Constructing Elephant!");
    }
    }
    static void Main(string[] args)
    {
    elephant e = new elephant();
    Console.ReadLine();
    }
        
    }
    }
    }
      

  3.   

    在函数里定义类..........无法编译当然要报错。C中没有类,但是也不允许在函数中定义函数的吧,至于VB,你真的这样定义过?
      

  4.   

    楼主的程序运行的没有问题只是没显示出下面的结果
    Constructing Animal!
    Constructing Elephant!tianlong30()的解答之所以能显示出上面的结果
    是因为他在MAIN函数里多了个Console.ReadLine();