How to add methods to manipulate an array of class objects?

こ雲淡風輕ζ 提交于 2021-02-08 04:41:09

问题


I didnt know how to word the question, so sorry if it doesnt really make sense, but it should start making sense here. Also, I am sorry if the solution is really, really simple. Google couldnt understand what I was asking (probs cause I was asking it wrong :P)

So I wrote a class that I called OrderSelection

In my program I need to have an array of OrderSelection objects, and I need to perform actions on this array (re-ordering, sorting etc).

What I am doing right now is keeping methods in the OrderSelection class that accept, among others, the array which you want to re-order, for example.

something like:

public void reorder(OrderSelection[] ord, int switchX, int switchY){....}

But What I want to be able to do is this:

OrderSelection[] order = new OrderSelection[10];
//do stuff
order.reorder(1,2);//which is WAY better than order[0].reorder(order, 1,2) as a horrid example

So yeah...how can I add these functions which I want to apply to an array of objects of my class?

thanks!


回答1:


You're looking for Extension Methods. Here's the MSDN documentation.

Writing an extension method looks like this:

public static class OrderSelectionExtensionMethods
{
    public static void reorder(this OrderSelection[] orders, int x, int y) 
    {
        // Do something with each order
    }
}

Extension methods are usually defined in an entirely separate class.
Also, two things are required for Extension Methods:

  • The entire class must be static
  • The first parameter for each extension method must have the keyword this before it

With the above code, your example code would compile fine:

OrderSelection[] order = new OrderSelection[10];
//do stuff
order.reorder(1,2);

This is the exact same as writing the following:

OrderSelection[] order = new OrderSelection[10];
//do stuff
OrderSelectionExtensionMethods.reorder(order, 1, 2);



回答2:


You should make your own collection class that inherits Collection<OrderSelection> and contains additional methods.




回答3:


I agree with Slaks, Making use of Generics and implementing Interfaces such as IEnumerable, ICollection will make your code cleaner and maintainable, for instance, by implementing the IEnumerable interface it makes possible to use the foreach statement. Depending on the complexity/size of your "OrderSelection" class you may decide the most suitable way to perform operations such as sorting. You may want to look at: http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx, http://support.microsoft.com/kb/320727,

I hope this helps



来源:https://stackoverflow.com/questions/8650831/how-to-add-methods-to-manipulate-an-array-of-class-objects

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