如何添加方法来操纵类对象的数组? [英] How to add methods to manipulate an array of class objects?
问题描述
我不知道该如何措辞,因此,如果这确实没有道理,那么我们感到抱歉,但是应该从这里开始变得有道理...................................................p.............另外,如果解决方案真的非常简单,我也感到抱歉.Google无法理解我的要求(问题可能是因为我问错了:P)
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)
所以我写了一个叫 OrderSelection
在我的程序中,我需要有一个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).
我现在正在做的是将方法保留在OrderSelection类中,这些方法可以接受(例如)您要重新排序的数组.
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.
类似:
public void reorder(OrderSelection[] ord, int switchX, int switchY){....}
但是我想做的是:
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?
谢谢!
推荐答案
您正在寻找扩展方法.这是MSDN文档.
编写扩展方法如下:
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:
- 整个类必须是
static
- 每个扩展方法的第一个参数前面必须带有关键字
this
使用上面的代码,您的示例代码可以正常编译:
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);
这篇关于如何添加方法来操纵类对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!