How to create a subclass in C#?

此生再无相见时 提交于 2019-11-29 11:40:08

问题


How do I create a subclass in C# for ASP.NET using Visual Studio 2010?


回答1:


Do you mean this?

public class Foo
{}

public class Bar : Foo
{}

In this case, Bar is the sub class.




回答2:


Here is an example of writing a ParentClass and then creating a ChildClass as a sub class.

using System;

public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }

    public void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}

public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }

    public static void Main()
    {
        ChildClass child = new ChildClass();

        child.print();
    }
}

Output:

Parent Constructor.
Child Constructor.
I'm a Parent Class.

Rather than rewriting yet another example of .Net inheritance I have copied a decent example from the C Sharp Station website.




回答3:


Do you mean class inheritance?

public class SubClass: MasterClass
{
}



回答4:


If you put a class in a class, it's kind of like one.

public class Class1
{
   public class Class2
   {
      public void method1() 
      {
         //Code goes here.
      }
   }
}

You can then reference the subclass using: Class1.Class2.method1().




回答5:


This page explains it well:

public class SavingsAccount : BankAccount
{
    public double interestRate;

    public SavingsAccount(string name, int number, int balance, double rate) : base(name, number)
    {
        accountBalance = balance;
        interestRate = rate;
    }

    public double monthlyInterest()
    {
        return interestRate * accountBalance;
    }
}

static void Main()
{
    SavingsAccount saveAccount = new SavingsAccount("Fred Wilson", 123456, 432, 0.02F);

    Console.WriteLine("Interest this Month = " + saveAccount.monthlyInterest());
}

If the monthlyInterest method already exists in the BankAccount class (and is declared abstract, virtual, or override) then the SavingsAccount method definition should include override, as explained here. Not using override to redefine such class methods will result in a CS0108 compiler warning, which can be suppressed by using new as confusingly stated here.



来源:https://stackoverflow.com/questions/4245816/how-to-create-a-subclass-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!