Ton*_*Nam 3 c# polymorphism inheritance
我有:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是当我这样做时:
Student.GenerateRandomInstance();
Run Code Online (Sandbox Code Playgroud)
我得到一个Person而不是一个Student.如何修复GenerateRandomInstance方法,使其返回Student而不是Person.将一个人投给学生会给我一个错误
你不能.静态方法不能在子类中重写,并且无法区分Student.GenerateRandomInstance和Person.GenerateRandomInstance- 实际上它们在编译时生成完全相同的CIL.
您可以使用通用方法:
public static T GenerateRandomInstance<T>() where T : Person, new
{
var p = new T();
// randomize properties
return p;
}
Person.GenerateRandomInstance<Student>();
Run Code Online (Sandbox Code Playgroud)
但这只有在类型具有无参数构造函数时才有效.如果您想将参数传递给构造函数,则会变得更加困难.假设您始终知道要将哪些值传递给构造函数,则可以执行以下操作:
public static T GenerateRandomInstance<T>() where T : Person
{
var p = (T)Activator.CreateInstance(typeof(T), "hello", 4);
// randomize properties
return p;
}
Run Code Online (Sandbox Code Playgroud)
当然,如果指定的类型不包含合适的构造函数,这也将失败.