实用程序类与子类化.net控件(utility class vs subclassing .net controls)

编程入门 行业动态 更新时间:2024-10-26 06:28:30
实用程序类与子类化.net控件(utility class vs subclassing .net controls)

我想重用一些我写的代码来为datagridview添加一些功能。 我想要公开默认的datagridview属性和事件,所以我不想创建一个新的自定义组件。 所以我试图写一个子类,它工作正常。 但是我也想到,我可以编写一个独立的实用程序类,它在构造函数中使用datagridview并将其设置为相同的方式。 例如

public class MyGrid { private DataGridView m_dg; public MyGrid(DataGridView dg) { m_dg = dg; m_dg.RowHeadersVisible = false; m_dg.SortCompare += new DataGridViewSortCompareEventHandler(m_dg_SortCompare); } void m_dg_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { // do custom sorting here } }

所以在我的应用程序的启动时我会打电话

MyGrid g1 = new MyGrid(dataGridView1); MyGrid g2 = new MyGrid(dataGridView2);

等等。 这种方法的缺点? 看起来大部分代码将会是相同的,区别在于你如何实例化扩展网格(拖放一个子类控件到窗体,拖动一个普通的datagridview并调用上面的代码)

I want to reuse some code I wrote to add some functionality to a datagridview. I want the default datagridview properties and events to be exposed, so I didn't want to create a new custom component. so I tried writing a subclass, which works fine. but it also occurred to me that I could write a standalone utility class that takes a datagridview in the constructor and sets it up the same way. e.g.

public class MyGrid { private DataGridView m_dg; public MyGrid(DataGridView dg) { m_dg = dg; m_dg.RowHeadersVisible = false; m_dg.SortCompare += new DataGridViewSortCompareEventHandler(m_dg_SortCompare); } void m_dg_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { // do custom sorting here } }

so somewhere in my app's startup I would call

MyGrid g1 = new MyGrid(dataGridView1); MyGrid g2 = new MyGrid(dataGridView2);

and so forth. any disadvantages to this approach? it seems like much of the code is going to be the same, the difference is between how you instantiate the extended grid (drag and drop a subclassed control to the form vs drag a plain datagridview and call the above code)

最满意答案

实用程序类的唯一缺点是您失去了设计者支持。 这意味着,如果您将控件进行子类化,将其添加到设计器中,则您在继承控件的构造函数中所做的任何更改都会显示在设计器中。 此外,如果您想添加一些属性,它们将显示在属性窗口中,使其具有更大的灵活性。 如果设计师的支持对你来说并不重要,那么我看不到公用事业的其他任何缺点。

The only disadvantage of a utility class, is that you lose the designer support. Meaning, if you subclass the control, when you add it to the designer, any changes you make in the constructor of your inherited control will show up in the designer. Furthermore, if you want to add some properties to it, they will show up in the properties window, giving it even more flexibility. If designer support doesn't matter to you though, then I don't see any other drawbacks to a utility class.

更多推荐

本文发布于:2023-07-28 08:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1303011.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   控件   实用程序   subclassing   controls

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!