我试图让我学习的新学生阅读about方法,但是about方法中的变量表示未分配。我以为是因为我在我制作的每个类中都将它们设置为默认值。
namespace studentHeirarchy
{
class Program
{
static void Main(string[] args)
{
runStudent();
}
static void runStudent()
{
Student one = new Student();
Console.WriteLine(one.About());
Console.ReadLine();
}
}
}
namespace studentHeirarchy
{
public class ColumbiaStudent : Student
{
public bool isInOOP;
public ColumbiaStudent()
{
isInOOP = true;
}
public String About()
{
string About = "my favorite course is OOP";
return About;
}
public void GetOOPString()
{
throw new System.NotImplementedException();
}
}
}
namespace studentHeirarchy
{
public class Student : Person
{
public int NumCourses;
public string SchoolName;
public Student()
{
NumCourses = 1;
SchoolName = "Columbia";
}
public string About()
{
string About = string.Format("my name is{0}, I am {1} years old, I attend {2} and am taking {3} courses."), Name, Age, SchoolName, NumCourses;
return About;
}
public void AddCourse()
{
throw new System.NotImplementedException();
}
public void DropCourse()
{
throw new System.NotImplementedException();
}
}
}
namespace studentHeirarchy
{
public class Person
{
public int Age;
public string Name;
public Person()
{
Age = 17;
Name = "Jeff";
}
public string About()
{
throw new System.NotImplementedException();
}
}
}
最佳答案
您的问题出在您的string.Format
上。您在关闭括号,然后认为您在声明其他变量:
string About = string.Format("my name is{0}, I am {1} years old, I attend {2} and am taking {3} courses."), Name, Age, SchoolName, NumCourses;
应该:
string About = string.Format("my name is{0}, I am {1} years old, I attend {2} and am taking {3} courses.", Name, Age, SchoolName, NumCourses);
解决此问题将产生输出:
我的名字叫杰夫,我今年17岁,我就读哥伦比亚大学,正在学习1门课程。
此外,我敦促您查看C#Polymorphism。这是另一个问题的核心,其他所有人的答案都被忽略了。具体来说,您需要了解
virtual
,override
和new
(new
,因为它与方法签名有关,与实例无关)。关于c# - 我如何获得about方法来读取变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22160514/