小编Edw*_* B.的帖子

解决'构造函数中的虚方法调用'问题

我在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

public virtual Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument) {
    throw new NotImplementedException("Real instruction not implemented. Instruction type: " + GetType());
}
Run Code Online (Sandbox Code Playgroud)

因此,Resharper告诉我,在标记的行中,我"在构造函数中调用虚方法"并且这很糟糕.我理解构造函数被调用的顺序.该GetRealInstruction方法的所有覆盖内容如下所示:

public override Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument) {
    return new GoInstruction(instructionSet, argument);
}
Run Code Online (Sandbox Code Playgroud)

所以他们不依赖于班上的任何数据; 他们只返回依赖于派生类型的东西.(因此构造函数顺序不会影响它们).

那么,我应该忽略它吗?我宁愿不; 所以任何人都可以告诉我如何避免这种警告?

我不能巧妙地使用委托,因为该GetRealInstruction方法还有一个重载.

c# resharper inheritance constructor

19
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×1

constructor ×1

inheritance ×1

resharper ×1