关于c#:构造函数中的这些虚拟成员调用警告是否合法?

Are these Virtual Member Call in Constructor warnings legitimate?

在我设置EditMyDataObject属性的基本表单中,以及在我获取文本值并在随后还原该值的扩展表单中,我将收到Resharper警告。

在这两种情况下,当我运行应用程序时,什么都不会爆炸。我认为在实现时没有任何潜在的问题,因为我的重写属性不依赖于构造函数中初始化的任何内容,但希望在阻塞Resharper之前给出第二个意见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
    }
}


只要每个派生类以一种不依赖于在该派生类的构造函数中初始化的变量的方式重写该虚拟成员,您就安全了。问题是,您不能知道从您的基类派生的每个类的行为都是这样的。因此,警告是合法的。