سؤال

Assume that you have the following method:

public static void TestMe <T>(Action action)
    {
        List<T> collection = new List<T>();
        //Stuff gets added to "collection" here
        action(collection);
    }

This will give a compiler error since the above have no parameters.

However, I don't want a parameter for the collection, since this will get filled in the TestMe method. If I correct the usage, it looks like this:

public static void TestMe <T>(Action<List<T>> action)
        {
            List<T> collection = new List<T>();
            //Stuff gets added to "collection" here
            action(collection);
        }

But I cant do this, because then when I call TestMe, it wants the collection to be available as a parameter. Is there anyway around this?

هل كانت مفيدة؟

المحلول

Let's test it:

public static void TestMe<T>(Action<List<T>> action)
{
    List<T> collection = new List<T>();
    collection.Add((T)(object)"123"); //I do not know, how you fill the collection
    action(collection);
}
  1. You can use lamda expression to specify the action; l here is just a parameter:

    TestMe<string>(l => l.ForEach(s => Console.WriteLine(s))); //outputs: 123
    
  2. You may specify a method with the necessary signature:

    public static void Foo<T>(List<T> list)
    {
        list.ForEach(s => Console.WriteLine(s));
    }
    

    and call TestMe then:

    TestMe<string>(Foo);     //outputs: 123
    

Both these examples show that your TestMe does not require the List<T> to be called and do use the collection specified within the TestMe method.


مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top