gpt4 book ai didi

C# 无法从抽象父类对象访问子公共(public)方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:44 25 4
gpt4 key购买 nike

我正在学习 OOAD 并尝试通过继承来实现类关系,但代码存在问题

父类

namespace ConsoleApplication1
{
abstract class Classification
{
public abstract string type();
}
}

第一个子类

namespace ConsoleApplication1
{
class FullTime : Classification
{
bool inCampus;
string roomDetail;
float rent;

public FullTime(string studentRoomDetail, float studentRent)
{
this.inCampus = true;
this.roomDetail = studentRoomDetail;
this.rent = studentRent;
}

public FullTime()
{
this.inCampus = false;
}

public string printAccommodationDescription()
{
if (!this.inCampus)
{
return "Not in campus";
}
else
{
return "Room: " + this.roomDetail + " Rent: " + this.rent.ToString();
}
}

public override string type()
{
return "fulltime";
}
}
}

第二个 child 类(class)

namespace ConsoleApplication1
{
class PartTime : Classification
{
bool onJob;
string jobTitle;
float salary;

public PartTime(string studentJobTitle, float studentSalary)
{
this.onJob = true;
this.jobTitle = studentJobTitle;
this.salary = studentSalary;

}

public PartTime()
{
this.onJob = false;
}

public string printJobDescription()
{
if (!this.onJob)
{
return "Not on job";
}
else
{
return "JobTitle: " + this.jobTitle + " Salary: " + this.salary.ToString();
}
}

public override string type()
{
return "parttime";
}
}
}

现在在 Program.cs 中,当我尝试从 PartTime 类访问方法 printJobDescription

Classification classification = new PartTime("Software Engineer", 10000);
classification.printJobDescription();

它说

Error CS1061 'Classification' does not contain a definition for 'printAccommodationDescription' and no extension method 'printAccommodationDescription' accepting a first argument of type 'Classification' could be found (are you missing a using directive or an assembly reference?)

我该如何解决这个问题?

更新

我需要让对象在运行时更改其类的能力,因此我必须创建类型为Classification 的对象并使用其他类中未实现的任一方法

最佳答案

您只能使用您使用的类中声明的函数。

abstract class Classification
{
public abstract string type();
}

class PartTime : Classification
{
public override string type() {...}
public Job1() {...}
}

class FullTime : Classification
{
public override string type() {...}
public Job2() {...}
}
  • Classification类型的对象只能使用type()
  • PartTime 类型的对象可以使用 type 和 Job1()
  • FullTime 类型的对象可以使用 type 和 Job2()

如果你有这样一个对象:

Classification classification = new PartTime();

并且您不知道是哪种特殊类型,您必须强制转换此对象才能使用其他方法:

if (classification is PartTime)
{
((PartTime)classification).Job1();
}
else if (classification is FullTime)
{
((FullTime)classification).Job2();
}

希望这对您有所帮助。

关于C# 无法从抽象父类对象访问子公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33974097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com