我正在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
這是非常深思熟慮,謝謝。我最終以另一種方式避免了這個問題,但這是未來非常好的解決方案。 –