我正在c#中制作软件。我使用的是抽象类,Instruction
,拥有这些代码位:解决'构造函数中的虚拟方法调用'问题
protected Instruction(InstructionSet instructionSet, ExpressionElement newArgument,
bool newDoesUseArgument, int newDefaultArgument, int newCostInBytes, bool newDoesUseRealInstruction) {
//Some stuff
if (DoesUseRealInstruction) {
//The warning appears here.
RealInstruction = GetRealInstruction(instructionSet, Argument);
}
}
和
public virtual Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument) {
throw new NotImplementedException("Real instruction not implemented. Instruction type: " + GetType());
}
所以ReSharper的告诉我,在标记线I AM“调用虚方法构造”这是不好的。我了解构造函数被调用的顺序。该GetRealInstruction
方法的所有覆盖这个样子:
public override Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument) {
return new GoInstruction(instructionSet, argument);
}
所以他们不依赖于任何同类数据;他们只是返回一些依赖派生类型的东西。 (所以构造函数的顺序不会影响它们)。
那么,我应该忽略它吗?我宁愿不;所以任何人都可以告诉我如何避免这种警告?
我不能使用委托整齐,因为GetRealInstruction
方法有一个更多的重载。
我忘了提及,但这种方式的另一个好处是,在你的情况下,你避免了基本方法虚拟的需要,而不是抽象的,因此你得到编译时检查,而不是抛出一个异常(@TarasDzyoba提到) 。 – Richard
这是非常深思熟虑,谢谢。我最终以另一种方式避免了这个问题,但这是未来非常好的解决方案。 –