【问题标题】:initializing the button初始化按钮
【发布时间】:2011-11-19 01:45:34
【问题描述】:

你好,我来自 c/c++ 的世界,我有以下 sn-p 的代码,用这种方式初始化按钮是个好主意吗?提前致谢

private Button initializeButton() {
    Button button = new Button();

    button.FlatStyle = System.Windows.Forms.FlatStyle.System;
    button.Location = new System.Drawing.Point(16, 16);
    button.Name = "button";
    button.Size = new System.Drawing.Size(168, 24);
    button.TabIndex = 5;
    button.Text = "button";

    return button;
}

【问题讨论】:

  • portButton 是什么?你的意思是button

标签: c#


【解决方案1】:

是的,如果你想让它更短,你可以使用这样的东西:

    private Button initializeButton() {
        return new Button() {
            FlatStyle = System.Windows.Forms.FlatStyle.System,
            Name = "button",
            ....
        };
    }

如果您不将其添加到父级的Controls collection,则可能需要dispose this button later

【讨论】:

    【解决方案2】:

    这完全没有错。但是,您也可以使用快捷语法:

    return new Button {
        FlatStyle = System.Windows.Forms.FlatStyle.System,
        Location = new System.Drawing.Point(16, 16),
        Name = "button",
        Size = new System.Drawing.Size(168, 24),
        TabIndex = 5,
        Text = "button"
    };
    

    【讨论】:

    • 可以这样分配事件吗?
    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2017-11-27
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多