我有:
class Person
{
public Person(string name, int age)
{
this.Name = name;
}
public string Name { get; set; }
public virtual void Speak()
{
Console.Write("Hello I am a person");
}
public static T GenerateRandomInstance<T>() where T: Person
{
var p = new T("hello", 4); // error does not compile
// rondomize properties
return p;
}
}
class Student : Person
{
// constructor I call the base class here
public Student(string name, int age)
: base(name, age)
{
}
public override void Speak()
{
Console.Write("Hello I am a student");
}
}
我遇到的问题是,当我这样做时:
Student.GenerateRandomInstance();
我得到 aPerson
而不是 a Student
。如何修复该GenerateRandomInstance
方法,使其返回一个学生而不是一个人。将一个人投射给学生会给我一个错误