Extension methods not allowed in nested static classes?

别说谁变了你拦得住时间么 提交于 2019-12-10 02:48:40

问题


Why is this? I would find it really nice to be able to have some extension methods locked down to be used only within one of my classes. Don't really want to have certain extension methods available everywhere... and they look so much nicer than regular static methods :P


For clarification:

The reason I want these extension methods is because I am extending a Form, which has a DataGridView on it. And I am getting very tired of lines like these:

foreach(var row in grid.Rows.OfType<DataGridViewRow>().Where(r => (bool) r.Cells[checkBoxColumn.Index].Value))

foreach(var row in grid.SelectedRows.OfType<DataGridViewRow>().Where(r => (bool) r.Cells[checkBoxColumn.Index].Value))

Would like an extension method so that I could just do

foreach(var row in grid.Rows.CheckedRows())

foreach(var row in grid.SelectedRows.CheckedRows())

So in other words, this extension method would not be useful at all outside this class. But it would make the code a lot cleaner. Can of course make regular methods too, and that is what I ended up doing, since this wasn't possible.

Aaanyways, I was just curious to know if anyone had some good arguments to why they had chosen to put a restriction like this upon where extension methods can created used. Must be in a static class makes total sense. Can't be in a nested static class doesn't... to me at least...


回答1:


Would using an extension method really make your code a lot cleaner than using a standard helper method on your class?

// extension method
foreach (var row in grid.Rows.CheckedRows())
foreach (var row in grid.SelectedRows.CheckedRows())

// standard helper method
foreach (var row in CheckedRows(grid.Rows))
foreach (var row in CheckedRows(grid.SelectedRows))



回答2:


If you own the source code of the type, why are you using extension methods? Why don't you just make those extension methods members of the type itself?

Extension methods are best used to extend types that you did not create. While they are useful tools they are a layer of indirection that should be a last resort rather than a first. While you can use them to extend your own types it makes more sense to reserve their use for types that you did not create.




回答3:


If you're extending a Type, then the extension methods should be as equaly accessible as the type itself.

Best practices also suggest putting all extension methods in one place, preferably in one static class or contained within a single namespace.



来源:https://stackoverflow.com/questions/772351/extension-methods-not-allowed-in-nested-static-classes

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