我希望找到使用Activator.CreateInstance()
函数调用继承类的重写函数的正确方法。我正在这样做,以便我可以基于字符串对象调用派生类的特定函数,以便字符串确定将创建哪个派生类对象并调用其函数。这样的事情,但我不知道如何正确地做,或者有比使用Activator更好的方法。
public class Test
{
public virtual void DefaultCalibration()
{
//Do nothing
}
}
public class EasyTest : Test
{
public override void DefaultCalibration()
{
//Do one thing
}
}
public class HardTest : Test
{
public override void DefaultCalibration()
{
//Do another thing
}
}
public class Tester
{
public void main()
{
string testName = "";
// ...
// ... Do some stuff to get a string of the name of the class, ie testName = "HardTest";
// ...
Type type = Type.GetType(testName);
object instance = Activator.CreateInstance(type);
((Test)instance).DefaultCalibration(); //this line doesn't call the derived function
}
}
我想要它,以便派生类'调用override函数而不是基类函数。
意图是如果我的字符串是" HardTest",那么它基本上就像
((HardTest)instance).DefaultCalibration();
但如果它是" EasyTest"然后它看起来像
((EasyTest)instance).DefaultCalibration();