Virtual member call in constructor [duplicate]

跟風遠走 提交于 2019-12-08 15:44:36

问题


In my application I am running the same winform in different contexts to control visibility of buttons, enabeling of text fields and the winform header text. The way I decided to do this is simply by passing a string to the form constructor and check it with a couple of if statements that in turn contain the desired winform tweaks.

if (formContext == "add")
{
    Text = "Add member";
}
if (formContext == "edit")
{
    Text = "Change role";
    userTextBox.Enabled = false;
    searchButton.Visible = false;
}

This works fine, however the "Text" keywords get a blue squigly line added by ReSharper with the following message: Viritual member call in constructor. Is this a potential problem or just some sort of overly enthusiastic ReSharper message.

Any clarification or suggestions for improvement of my implementation would be much appreciated.


回答1:


A virtual member call in the base class ctor could cause some logic to run in the subclass before the subclass' ctor is called (and thus before the object gets a chance to initialize itself to a consistent state).

It's just a nice reminder so you know you are doing something that could potentially cause some nasty unexpected behavior.




回答2:


In addition to the existing answers, for forms you could add a Load event handler:

Load += delegate
{
    if (formContext == "add")
    {
        Text = "Add member";
    }
    if (formContext == "edit")
    {
        Text = "Change role";
        userTextBox.Enabled = false;
        searchkButton.Visible = false;
    }
};



回答3:


Just seal your class.




回答4:


I would suggest rewriting you class as follows:

public partial class Form1 : Form
{
    public enum FormContextMode
    {
        Add,
        Edit
    }

    private FormContextMode m_mode = FormContextMode.Add; 

    public Form1( FormContextMode mode )
    {
        InitializeComponent();
        m_mode = mode;
        Load += delegate { UpdateForm(); };
    }

    private void UpdateForm()
    {
        if( m_mode == FormContextMode.Add )
        {
            Text = "Add member";    
        }
        else if( m_mode == FormContextMode.Edit )
        {
            Text = "Change role";
            userTextBox.Enabled = false;
            searchkButton.Visible = false;
        }
    }
}


来源:https://stackoverflow.com/questions/457482/virtual-member-call-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!