继承,重写方法和构造函数

时间:2012-07-29 02:06:32

标签: c# inheritance constructor

这是我的代码。我正在尝试在其中进行一些基本的继承,但显示方法似乎不起作用。我认为它与构造函数有关,所以我已经放了一个“base(a,b,c);”那里。 :)

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

namespace School
{
    public class CollegeCourse
    {
        public CollegeCourse(String a, int b, double c)
        {
            dep = a;
             kors = b;
             cre = c;

        }
        public String dep;
        public int kors;
        public double cre;
        public double fee;

        public String getDep()
        { return dep; }

        public int getKors()
        { return kors; }
        public double getCre()
        { return cre; }

        public virtual void display()
        {
            fee = cre * 120;
            Console.WriteLine("Dep is : {0}\n"+
                " Course is : {1}\n Credit is : {2}\nFee is : {3}", 
                getDep(), getKors(), getCre(), fee);
        }
    }


    public class LabCourse : CollegeCourse
    {
        public LabCourse(String a, int b, double c)
            : base(a, b, c)
        {
             dep = a;
            kors = b;
             cre = c;

        }
        public override void display()
        {
            fee = cre * 120;
            Console.WriteLine(@"Dep is : {0}\n "+ 
                "Course is : {1}\n Credit is : {2}\nFee is : {3}", 
                dep, kors, cre, fee + 50);
        }
    }

    public class UseCourse
    {
        public static void teste()
        {
            String a;
            int b;
            double c;
            Console.WriteLine("Input Department:");
            a = Console.ReadLine();
            Console.WriteLine("Input Course:");
            b = Int16.Parse(Console.ReadLine());
            Console.WriteLine("Input Credits:");
            c = Double.Parse(Console.ReadLine());
            CollegeCourse aw = new CollegeCourse(a, b, c);
            LabCourse oy = new LabCourse(a, b, c);
            aw.display();
            oy.display();
            Console.ReadLine();
        }
    }

}

2 个答案:

答案 0 :(得分:1)

在构造函数中,您正在创建新的局部变量(在构造函数中)而不是在类中设置属性。

如果您删除CollegeCourse构造函数中的类型定义,这应该可以解决您的问题:

    public CollegeCourse(String a, int b, double c)
    {
        dep = a;
        kors = b;
        cre = c;

    }

在LabCourse中,您不需要设置任何属性,因为您使用传递给LabCourse构造函数的参数调用继承的构造函数:

    public LabCourse(String a, int b, double c)
        : base(a, b, c)
    {
    }

答案 1 :(得分:0)

在构造函数中,您将创建三个与您的字段同名的全新局部变量,这就是它们未被设置的原因。以下是一个如何设置类的示例:

public class Shape
{
    private int _sides;
    public int Sides
    {
         get { return _sides; }
         set { _sides = value; }
    }

    public Shape(int sides)
    {
        Sides = sides;
    }
}

请注意,字段通常是私有的,属性是公共的,以及如何将传递给构造函数的参数分配给属性或字段。