简体   繁体   English

C#将一个Func <T,List <myClass >>数组传递给一个方法

[英]C# Passing an array of Func<T, List<myClass>> to a method

My first (and really horrible post) is below. 我的第一个(也是非常可怕的帖子)在下面。

I try to do a complete example what I want to get. 我试着做一个完整的例子,我想得到什么。 I hope this will be left explained a bit better. 我希望这会更好地解释一下。

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Boy> boys = new List<Boy>();
            boys.Add(new Boy("Jhon", 7));
            boys.Add(new Boy("Oscar", 6));
            boys.Add(new Boy("Oscar", 7));
            boys.Add(new Boy("Peter", 5));
            ClassRoom myClass = new ClassRoom(boys);

            Console.WriteLine(myClass.ByName("Oscar").Count);  // Prints 2
            Console.WriteLine(myClass.ByYearsOld(7).Count);  // Prints 2

            // This has errors...................
            // But this is as I would like to call my BySomeConditions method....
            Console.WriteLine(  // It should print 1
                                myClass.BySomeConditions([myClass.ByName("Oscar"),
                                                          myClass.ByYearsOld(7)]
                                                        )
                             );
            Console.ReadKey();
        }





        class ClassRoom
        {
            private List<Boy> students;

            public ClassRoom(List<Boy> students)
            {
                this.students = students;
            }

            public List<Boy> ByName(string name)
            {
                return students.FindAll(x => x.Name == name);
            }
            public List<Boy> ByYearsOld(int yearsOld)
            {
                return students.FindAll(x => x.YearsOld == yearsOld);
            }

            // This has ERRORS.......................
            public List<Boy> BySomeConditions(params Func<X, List<Boy>>[] conditions)
            {
                IEnumerable<Boy> result = students;                
                foreach (var condition in conditions) {
                    // I want it ONLY be called with existent functions (ByName and/or ByYearsOld)
                    result = result.Intersect(condition(this));  
                }
            }
        }


        class Boy
        {
            public string Name { get; set; }
            public int YearsOld { get; set; }
            public Boy(string name, int yearsOld)
            {
                Name = name;
                YearsOld = yearsOld;
            }
        }
    }
}

============== first post ===================== Hello, ==============第一篇文章=====================你好,

I have a class with methods: 我有一个方法类:

public class X
{
    private readonly List<string> myList;

    public X(List<string> paramList) // string is really an object
    {
         myList = paramList;
    }

    // Now I want this...
    public List<string> CheckConditions(params Func<T, List<string>>[] conditions)
    {
         var result = myList;
         foreach (Func<T, List<string>> condition in conditions)
         {
               result = result.Intersect(condition(T));
         }
    }

    public List<string> check1(string S)
    {
         return myList.FindAll(x => x.FieldS == S);
    }
    public List<string> check1(int I)
    {
         return myList.FindAll(x => x.FieldI == I);
    }
}

Sorry if there is some error, I have written from scrach to avoid complex real case. 对不起,如果有一些错误,我已经写了刮,以避免复杂的实际情况。

What I want is call my methods like this: 我想要的是调用我的方法:

   X.check1("Jhon");

or 要么

   X.check2(12);

or ( this is the goal of my question ): 或( 这是我的问题的目标 ):

   X.CheckConditions(X.check1("Jhon"), X.chek2(12));

Thanks and sorry by my poor example... 我的可怜的榜样感谢和抱歉......

It is unclear where your T comes from. 目前还不清楚你的T来自哪里。

Does this meet your requirements? 这符合您的要求吗?

public class X<T>
{
  private List<T> myList;

  public List<T> CheckConditions(params Func<T, bool>[] conditions)
  {
    IEnumerable<T> query = myList;
    foreach (Func<T, bool> condition in conditions)
    {
      query = query.Where(condition);
    }
    return query.ToList();
  }
}

Then later: 然后呢:

List<T> result = X.CheckConditions(
  z => z.FieldS == "Jhon",
  z => z.FieldI == 12
);

You need to change the method signature of CheckConditions , it's accepting a variable number of List<string> , not functions. 您需要更改CheckConditions的方法签名,它接受可变数量的List<string> ,而不是函数。

public List<string> CheckConditions(params List<string>[] lists)

The return type of check1 is List<string> , so that needs to be the type of the parameter that CheckConditions accepts. check1的返回类型是List<string> ,因此需要是CheckConditions接受的参数的类型。

There's no reason to make it generic, you know that you want to operate on the current instance of X (so pass in this , instead of the T type parameter). 没有理由使它成为通用的,你知道你想要操作当前的X实例(所以传入this ,而不是T类型参数)。 You need to cleanup a few things to to get it to compile (return result and make the type of result and the Intersect call compatible). 您需要清理一些东西以使其编译(返回result并使result类型和Intersect调用兼容)。 You can define it like this: 您可以这样定义:

public List<string> CheckConditions(params Func<X, List<string>>[] conditions)
{
     IEnumerable<string> result = myList;
     foreach (var condition in conditions)
     {
           result = result.Intersect(condition(this));
     }

     return result.ToList();
}

Ant then call it like this: 然后Ant像这样调用它:

xInstance.CheckConditions(x => x.check1("JHon"), x => x.check1(12));

All that said, I'm not sure why you wouldn't just pass around the results of these functions, instead of passing the actual functions around: 所有这一切,我不确定为什么你不会只是传递这些函数的结果,而不是传递实际的函数:

public List<string> CheckConditions(params List<string>[] conditions)
{
     IEnumerable<string> result = myList;
     foreach (var condition in conditions)
     {
           result = result.Intersect(condition);
     }

     return result.ToList();
}

Then call it as in your example, rather than passing in lambda expressions. 然后在您的示例中调用它,而不是传递lambda表达式。

What you pass to your 你传递给你的是什么

X.CheckConditions

is not a reference to the functions, but the returned value of their invocation. 不是对函数的引用,而是它们的调用的返回值。

Now, if you pass function reference - it does not come with parameters, unless you construct and pass a data-structure that will contain the function reference and the arguments it should work on. 现在,如果你传递函数引用 - 它没有参数,除非你构造并传递一个包含函数引用和它应该处理的参数的数据结构

In this case - generics is not the solution. 在这种情况下 - 泛型不是解决方案。 You should consider another pattern to follow, like command pattern or strategy pattern, where you pass to your CheckConstruction instances of checker-objects, each is instantiated with the parameters it should work on, and either implements or is provided by the validation function. 您应该考虑另一种模式,例如命令模式或策略模式,您将其传递给CheckConstruction -objects的CheckConstruction实例,每个模式都应该使用它应该处理的参数进行实例化,并且由验证函数实现或提供。

you could rewrite you function to look like this: 你可以重写你的功能看起来像这样:

// Now I want this...
    public List<string> CheckConditions(params Func<T, List<string>>[] conditions)
    {
         var result = myList;
         foreach (Func<T, List<string>> condition in conditions)
         {
               result = result.Intersect(condition(T));
         }
    }

your call would then be X.CheckConditions(()=>X.check1("Jhon"), ()=>X.chek2(12)); 你的调用将是X.CheckConditions(()=>X.check1("Jhon"), ()=>X.chek2(12));

and you need to provide an instance for x (since the methods are instance methods and not static methods) 并且您需要为x提供一个实例(因为这些方法是实例方法而不是静态方法)

In your example you pass T as an argument to the functor but T is a type argument som it can't be passed as an argument to the method. 在您的示例中,您将T作为参数传递给仿函数,但T是一个类型参数,因为它不能作为参数传递给方法。 Did you mean to pass a value? 你的意思是传递一个值吗?

This begs for a clarification of why you would want to do this. 这需要澄清您为什么要这样做。 Maybe if you provided details on what you are trying to accomplish (as opposed to how) then you could get a better solution to your problem. 也许如果您提供了有关您要完成的任务的详细信息(而不是如何),那么您可以更好地解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM