是否可以使用方法参数作为数组扩展方法

Is it possible to use a method argument as an array extension method

我试图将一个参数传递给一个方法,然后将该参数用作数组扩展方法,但我很挣扎。我的代码是:

//create method
public static void BankChoice(string SearchItem)
{
    //declare variables
    double tempMin = 0;
    int minIndex = 0;

    //set a temporary double as the first index of array
    tempMin = Program.array_SH1[0].SearchItem;

    //start loop to go through whole array
    for (int y = 0; y <= array_SH1.Length; y++)
    {
        //if the temp double is bigger than the array item, 
        //make array item temp double
        if (tempMin > array_SH1[y].SearchItem)
        {
            tempMin = array_SH1[y].SearchItem;
            minIndex = y;
        }
    }
}

然后我会将代码称为:

BankChoice("OpenPrice")

但是这不起作用。编译器不会接受字符串作为数组扩展,它只会抛出错误。 有没有办法解决这个问题而不必手写,并为 SearchItem

的所有变体创建一个方法

谢谢

你可以做的是提供一个委托:

public static void BankChoice(Func<ArrayValueType, double> searchBy)
{
    //...
    // use the delegate to evaluate the result for each time you need to get the value from an item in your array.
    tempMin = searchBy(Program.array_SH1[0]);
    //...
}

其中 ArrayValueType 是数组中对象的类型。然后你用

调用它
BankChoice(x => x.OpenPrice);

这将允许您指定 属性 进行搜索,并且将以类型安全的方式完成。目前唯一的限制是 属性 可以转换为 double。对于泛型类型的属性,可以绕过它,并且根据您的需要,有多种方法可以做到这一点。