如何将 ToUpper 或 ToLower 作为参数传递给方法?

问题描述

我四处寻找将 toupper 或 ToLower 作为参数传递的方法。我查看了操作,查看了委托,查看了扩展方法,还查看了 Microsoft 文档。我得到的最接近的答案是:Passing an extension method to a method expecting a delegate. How does this work?,但这并没有真正解释如何去做。我正在写这个问题以防其他人遇到类似的问题。例如,您不能将 string.ToLower() 作为参数传递。

问题正在解决

  1. 如何调用 string.toLower() 作为委托?

我想要做的事情的例子:

orderItems.GetContatenatedModdednames(string.ToLower());
orderItems.GetConcatenatedModdednames(string.toupper());

示例思想是能够将 ToLower() 或 toupper() 作为参数传入。

解决方法

这是一个如何做的例子......它涉及传递一个匿名函数。

public static string GetConcatenatedNames(this ICollection<OrderItem> orderItems,string separater = ",",Func<string,string> myFunc = null)
{
    if (myFunc == null)
    {
        myFunc = x => x.ToLower();
    }

    var productNames = orderItems?.Select(x => x.Product)?.Select(x => myFunc(x.ProductName));

    if (productNames == null)
    {
        return null;
    }

    return string.Join(separater,productNames);
}

调用:

var upperCaseNames = orderItems.GetConcatenatedConcessionNames(myFunc: x => x.ToUpper());