当它们分别传递给Action 时,如何访问List 中的对象?

时间:2021-04-28 18:36:49

Apologies if this is a duplicate but I can't find it.

如果这是重复的道歉,但我找不到它。

Here is the essence of my problem. Let's assume I have a List<T> containing dynamic objects:

这是我的问题的本质。假设我有一个包含动态对象的List :

var collection = new List<dynamic> 
{
    new { Foo = 1, Bar = "Test Text..."},
    new { Foo = 2, Bar = "Test Text #2..."},
    new { Foo = 3, Bar = "Test Text #3..."},
};

Now, imagine we want to iterate over this collection, and pass each dynamic to an Action<T>. Specifically in my case, I need to pass my objects into a Parallel.Foreach call. I've been able to construct the following code and the application can properly build.

现在,假设我们想迭代这个集合,并将每个动态传递给Action 。特别是在我的情况下,我需要将我的对象传递给Parallel.Foreach调用。我已经能够构造以下代码,并且应用程序可以正确构建。

Parallel.ForEach(collection, (s) => 
    { 
        Console.WriteLine("Success!");
    });

Of course, this is essentially useless until we operate on the parameter. What I need to do is access the s parameter within the lambda.

当然,在我们对参数进行操作之前,这基本上是无用的。我需要做的是访问lambda中的s参数。

Something like this:

像这样的东西:

Parallel.ForEach(collection, (s) => 
    { 
        Console.WriteLine("Foo = {0}, Bar = {1}", s.Foo, s.Bar);
    });

However, when I try to write such code I get a VS error stating:

但是,当我尝试编写这样的代码时,我得到一个VS错误说明:

One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?

无法找到编译动态表达式所需的一种或多种类型。你错过了参考吗?

How can I access my dynamic object from within my lambda expression?

如何从我的lambda表达式中访问我的动态对象?

1 个解决方案

#1


This is correct syntax. The project was missing a reference to the Microsoft.CSharp .Net assembly. (Doh!)

这是正确的语法。该项目缺少对Microsoft.CSharp .Net程序集的引用。 (DOH!)

#1


This is correct syntax. The project was missing a reference to the Microsoft.CSharp .Net assembly. (Doh!)

这是正确的语法。该项目缺少对Microsoft.CSharp .Net程序集的引用。 (DOH!)