这些构件中的虚拟成员呼叫警告是否合法?

时间:2011-12-09 14:50:29

标签: c# winforms inheritance resharper

我在这里以我设置EditMyDataObject属性的基本形式获取Resharper警告,并在扩展形式中获取Text值,然后恢复它。

在这两种情况下,当我运行应用程序时,没有任何东西在爆炸。我认为实现的问题没有任何可能性,因为我的重写属性不依赖于构造函数中初始化的任何内容,但是在扼杀Resharper之前会感激第二意见。

public class MyDataObject
{
    //Data Members

    public MyDataObject()
    {
    }
}

public class MyDataObjectEx : MyDataObject
{
    //Data Members

    public MyDataObjectEx()
    {
    }

    public MyDataObjectEx(MyDataObject myDataObject)
    {
    }       
}

public partial class MyDataObjectEditFrm : Form
{
    private MyDataObject _myDataObject;

    protected virtual MyDataObject EditMyDataObject
    {
        get { return _myDataObject; }
        set { _myDataObject = value; }
    }

    /// <summary>
    /// Parameterless constructor needed for designer support of derived classes.
    /// </summary>
    protected MyDataObjectEditFrm()
    {
        InitializeComponent();
    }

    protected MyDataObjectEditFrm(MyDataObject myDataObject)
    {
        InitializeComponent();
        EditMyDataObject = myDataObject;  // Warning: Virtual member call in a constructor

        Text = GetDialogNameFromInputParameters()

        //Remainder of initialization here
    }

    GetDialogNameFromInputParameters()
    {
        //Figure out what the text should be
    }
}


public partial class MyDataObjectExEditFrm : MyDataObjectEditFrm
{
    private MyDataObjectEx _myDataObjectEx;

    protected override MyDataObject EditMyDataObject
    {
        get { return _myDataObjectEx; }
        set
        {
            if (value == null)
                _myDataObjectEx = null;
            else _myDataObjectEx = value as MyDataObjectEx ?? new MyDataObjectEx(value);
        }

    }

    public MyDataObjectExEditFrm(MyDataObject myDataObject) : base(myDataObject)
    {
        //preserve the value computed and set in the base class to prevent the generic form name from the designer overriding it here
        string dialogText = Text; // Warning: Virtual member call in a constructor
        InitializeComponent();
        Text = dialogText; // Warning: Virtual member call in a constructor


        //Remainder of additional initialization for extended data here
    }
}

1 个答案:

答案 0 :(得分:6)

只要每个派生类以不依赖于在派生类的构造函数中初始化的变量的方式覆盖此虚拟成员,就是安全的。问题是,你不可能知道从你的基类派生的每个类都表现得像这样。因此,警告是合法的。