C# lambda expressions as function arguments

前端 未结 5 1294
礼貌的吻别
礼貌的吻别 2020-12-28 16:52

I\'ve been busy diving into lambda expressions recently, and there\'s some specific functionality that I\'ve been meaning to learn but just couldn\'t seem to make heads or t

相关标签:
5条回答
  • 2020-12-28 17:19

    You're looking for Action<> and Func<>.

    0 讨论(0)
  • 2020-12-28 17:19

    You can create extension

    public static class MakeArrayExtension
    {
        public static U[] MakeArray<T, U>(this IEnumerable<T> collection, Func<T,U> func)
        {
            return collection.Select(func).ToArray();
        }
    }
    

    And then use it like this

    List<A> foo; // assuming this is populated
    string[] bar = foo.MakeArray<A,string>(x => x.StringProperty);
    
    0 讨论(0)
  • 2020-12-28 17:32
    public static U[] MakeArray<T, U>(this IEnumerable<T> @enum, Func<T, U> rule)
    {
        return @enum.Select(rule).ToArray();
    }
    
    0 讨论(0)
  • 2020-12-28 17:34

    You can use the Func and Action classes. Check out the LINQ Where function's signature for an example: http://msdn.microsoft.com/en-us/library/bb534803.aspx

    0 讨论(0)
  • 2020-12-28 17:37

    Try the following

    U[] MakeArray<T,U>(Func<T, U> projection) where T : IEntity {
      ...
    }
    

    When passing lambdas as arguments you generally want the matching parameter to be a delegate. In most cases you should just use the appropriate Action<> or Func<> value. The former for void returning lambdas and the latter for ones that return values.

    0 讨论(0)
提交回复
热议问题