我刚开始使用c#几小时前,我看到了在c#中创建类的技巧。我创建了自己的两个类Animal and Dog,其中Dog继承Animal。我的代码没有错误,但我的程序仍然在执行时崩溃。我对oop有一点了解。我在这段代码中遗漏了一些重要内容吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultipleClasses
{
class Animal
{
public int hands;
public Boolean feathers;
public int legs;
public int getlegs(){ return legs; }
public void setlegs(int l){this.legs = l;}
public void sethands(int h){this.hands = h;}
public int gethands(){return this.hands;}
public void setfeathers(Boolean f){this.feathers = f;}
public Boolean getfeathers(){return this.feathers;}
public Animal(int l=0, int h=0, Boolean f=false){
this.legs = l;
this.hands = h;
this.feathers = f;
}
}
class Dog : Animal
{
public string name;
public int age;
public string getname(){return this.name;}
public int getage(){return this.age;}
public void setname(string n) { this.name = n;}
public void setage(int g){this.age = g;}
public Dog(string n, int g, int l, int h, Boolean f) : base(l, h, f)
{
this.name = n;
this.age = g;
}
}
class Program
{
static void Main(string[] args)
{
Dog a = new Dog("Jack",5,4,0,false);
Console.WriteLine("The Dog's name is {0} and age is {1} "+a.getname(),a.getage());
}
}
}
答案 0 :(得分:1)
问题是这一行:
Console.WriteLine("The Dog's name is {0} and age is {1} "+a.getname(),a.getage());
将+
更改为,
Console.WriteLine("The Dog's name is {0} and age is {1} ", a.getname(),a.getage());
更正后的输出:
狗的名字是杰克,年龄是5岁
代码还有其他问题,也就是你用某些东西命名的方式,你可能也想阅读有关getter和setter的内容。
答案 1 :(得分:0)
重新编写C#方式代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultipleClasses
{
class Animal
{
public int hands { get; set; }
public Boolean feathers { get; set; }
public int legs { get; set; }
public Animal(int l = 0, int h = 0, Boolean f = false)
{
this.legs = l;
this.hands = h;
this.feathers = f;
}
}
class Dog : Animal
{
public string name { get; set; }
public int age { get; set; }
public Dog(string n, int g, int l, int h, Boolean f)
{
this.name = n;
this.age = g;
this.legs = l;
this.hands = h;
this.feathers = f;
}
}
class Program
{
static void Main(string[] args)
{
Dog a = new Dog("Jack", 5, 4, 0, false);
Console.WriteLine("The Dog's name is {0} and age is {1}", a.name.ToString(), a.age.ToString());
}
}
}