19

I am making a software in c#. I am using an abstract class, Instruction, that has these bits of code:

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);
    }
}

and

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

So Resharper tells me that at the marked line I am 'calling a virtual method in constructor' and that this is bad. I understand the thing about the order in which the constructors are called. All overrides of the GetRealInstruction method look like this:

public override Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument) {
    return new GoInstruction(instructionSet, argument);
}

So they don't depend on any data in the class; they just return something that depends on the derived type. (so the constructor order doesn't affect them).

So, should I ignore it? I'd rather not; so could anyone show me how could I avoid this warning?

I cannot use delegates neatly because the GetRealInstruction method has one more overload.

4

5 回答 5

20

我已经多次遇到这个问题,我发现正确解决它的最佳方法是将构造函数调用的虚拟方法抽象到一个单独的类中。然后,您会将这个新类的实例传递给原始抽象类的构造函数,每个派生类将其自己的版本传递给基构造函数。解释起来有点棘手,所以我会根据你的例子举一个例子。

public abstract class Instruction
{
    protected Instruction(InstructionSet instructionSet, ExpressionElement argument, RealInstructionGetter realInstructionGetter)
    {
        if (realInstructionGetter != null)
        {
            RealInstruction = realInstructionGetter.GetRealInstruction(instructionSet, argument);
        }
    }

    public Instruction RealInstruction { get; set; }

    // Abstracted what used to be the virtual method, into it's own class that itself can be inherited from.
    // When doing this I often make them inner/nested classes as they're not usually relevant to any other classes.
    // There's nothing stopping you from making this a standalone class of it's own though.
    protected abstract class RealInstructionGetter
    {
        public abstract Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument);
    }
}

// A sample derived Instruction class
public class FooInstruction : Instruction
{
    // Passes a concrete instance of a RealInstructorGetter class
    public FooInstruction(InstructionSet instructionSet, ExpressionElement argument) 
        : base(instructionSet, argument, new FooInstructionGetter())
    {
    }

    // Inherits from the nested base class we created above.
    private class FooInstructionGetter : RealInstructionGetter
    {
        public override Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument)
        {
            // Returns a specific real instruction
            return new FooRealInstuction(instructionSet, argument);
        }
    }
}

// Another sample derived Instruction classs showing how you effictively "override" the RealInstruction that is passed to the base class.
public class BarInstruction : Instruction
{
    public BarInstruction(InstructionSet instructionSet, ExpressionElement argument)
        : base(instructionSet, argument, new BarInstructionGetter())
    {
    }

    private class BarInstructionGetter : RealInstructionGetter
    {
        public override Instruction GetRealInstruction(InstructionSet instructionSet, ExpressionElement argument)
        {
            // We return a different real instruction this time.
            return new BarRealInstuction(instructionSet, argument);
        }
    }
}

在您的特定示例中,它确实有点令人困惑,并且我开始用完合理的名称,但这是因为您已经在指令中嵌套了指令,即指令具有 RealInstruction(或至少可选) ; 但正如您所看到的,仍然可以实现您想要的并避免来自构造函数的任何虚拟成员调用。

如果还不清楚,我还将根据我最近在自己的代码中使用的示例给出一个示例。在这种情况下,我有 2 种类型的表单,标题表单和消息表单,它们都继承自基本表单。所有表单都有字段,但每种表单类型都有不同的构造字段的机制,所以我最初有一个名为 GetOrderedFields 的抽象方法,我从基本构造函数中调用它,并且在每个派生表单类中都覆盖了该方法。这给了我你提到的更清晰的警告。我的解决方案与上面的模式相同,如下

internal abstract class FormInfo
{
    private readonly TmwFormFieldInfo[] _orderedFields;

    protected FormInfo(OrderedFieldReader fieldReader)
    {
        _orderedFields = fieldReader.GetOrderedFields(formType);
    }

    protected abstract class OrderedFieldReader
    {
        public abstract TmwFormFieldInfo[] GetOrderedFields(Type formType);
    }
}

internal sealed class HeaderFormInfo : FormInfo
{
    public HeaderFormInfo()
        : base(new OrderedHeaderFieldReader())
    {
    }

    private sealed class OrderedHeaderFieldReader : OrderedFieldReader
    {
        public override TmwFormFieldInfo[] GetOrderedFields(Type formType)
        {
            // Return the header fields
        }
    }
}

internal class MessageFormInfo : FormInfo
{
    public MessageFormInfo()
        : base(new OrderedMessageFieldReader())
    {
    }

    private sealed class OrderedMessageFieldReader : OrderedFieldReader
    {
        public override TmwFormFieldInfo[] GetOrderedFields(Type formType)
        {
            // Return the message fields
        }
    }
}
于 2014-04-22T04:54:52.330 回答
2

您可以引入另一个抽象类 RealInstructionBase,这样您的代码将如下所示:

public abstract class Instruction {
   public Instruction() {
       // do common stuff
   }
}

public abstract class RealInstructionBase : Instruction {
   public RealInstructionBase() : base() {
       GetRealInstruction();
   }

   protected abstract object GetRealInstruction();
}

现在需要使用 RealInstruction 的每条指令都从 RealInstructionBase 派生,而所有其他指令都从 Instruction 派生。这样,您应该将它们全部正确初始化。

编辑:好的,这只会给你一个更干净的设计(如果在构造函数中没有),但不会消除警告。现在,如果您想知道为什么会首先收到警告,可以参考这个问题。基本上,关键是当您将实现抽象方法的类标记为密封时,您将是安全的。

于 2013-08-01T12:31:55.173 回答
2

当您创建派生类的实例时,您的调用堆栈将如下所示:

GetRealInstruction()
BaseContructor()
DerivedConstructor()

GetRealInstruction在派生类中被重写,其构造函数尚未完成运行。

我不知道你的其他代码看起来如何,但你应该首先检查在这种情况下你是否真的需要一个成员变量。你有一个方法可以返回你需要的对象。如果您确实需要它,请创建一个属性并调用GetRealInstruction()getter。

你也可以做GetRealInstruction抽象。这样你就不必抛出异常,如果你忘记在派生类中重写它,编译器会给你一个错误。

于 2013-08-01T11:40:43.977 回答
1

您可以将真实指令传递给基类构造函数:

protected Instruction(..., Instruction realInstruction)
{
    //Some stuff

    if (DoesUseRealInstruction) {
        RealInstruction = realInstruction;
    }
}

public DerivedInstruction(...)
    : base(..., GetRealInstruction(...))
{
}

或者,如果你真的想从你的构造函数中调用一个虚函数(我非常反对你),你可以抑制 ReSharper 警告:

// ReSharper disable DoNotCallOverridableMethodsInConstructor
    RealInstruction = GetRealInstruction(instructionSet, Argument);
// ReSharper restore DoNotCallOverridableMethodsInConstructor
于 2013-08-01T10:28:56.830 回答
0

另一种选择是引入一种Initialize()方法,您可以在其中执行需要完全构造的对象的所有初始化。

于 2016-08-15T04:01:44.387 回答