使用Extension方法设置默认属性是一种好习惯吗?

时间:2013-07-19 16:15:09

标签: c# .net-3.5 extension-methods

我正在使用一组第三方控件,我正在考虑使用扩展方法来设置几乎在应用程序中使用此控件时所需的一些属性。

为这种用途构建扩展方法是一种好习惯吗?为什么或为什么不呢?

有关更多详细信息,第三方库是DevExpress,我想要编写的扩展方法将禁用对其特定控件的所有自定义和编辑。

所以不要写

barManager.AllowCustomization = false;
barManager.AllowMoveBarOnToolbar = false;
barManager.AllowQuickCustomization = false;
barManager.AllowShowToolbarsPopup = false;
barManager.AutoSaveInRegistry = false;
foreach (Bar bar in barManager.Bars)
{
    bar.OptionsBar.DrawDragBorder = false;
}

我可以写

barManager.DisableEditing();

1 个答案:

答案 0 :(得分:5)

是的,你绝对可以这样做。因为扩展方法只是static方法的语法糖,并且你想构建一些静态辅助方法来配置一个给定的对象实例,所以它是有道理的。

仅仅为了完整性,有时使用与流畅界面相关的扩展方法来完成控制配置:

public static class DataGridExtensions
{
    public static DataGrid AllowColumnConfiguration(this DataGrid grid)
    {
        // Add NRE check
        grid.CanUserResizeColumns = true;
        grid.CanUserSortColumns = true;
        grid.CanUserReorderColumns = true;

        return grid;
    }

    public static DataGrid AllowEdition(this DataGrid grid)
    {
        // Add NRE check
        grid.CanUserAddRows = true;
        grid.CanUserDeleteRows = true;

        return grid;
    }
}

所以你可以这样使用它:

var grid = new DataGrid()
    .AllowColumnConfiguration()
    .AllowEdition();
相关问题