System.Action的 Lambda 表达式示例对于 MEF 案例?
我是 System.Action
using System;
using System.ComponentModel.Composition;
public class MyClass {
public static CompositionContainer Container = new CompositionContainer();
private void Initialize(Action<CompositonBatch> action) {}
public MyClass() {
CompositionBatch batch = null;
inititialize(x=> {
// create catalog instances: instance1 and instance2 as example
// ...
x.AddPart(instance1);
x.AddPart(instance2);
batch = x;
});
// at this point, will be batch be none-null value will parts added?
// the following code is composing batch to the container
Container.Compose(batch);
}
}
基本上,方法 Initialize(Action
我不确定我是否使用 System.Action
I am new to System.Action<T> and Lambda expression. Here is one case I would like to use.
using System;
using System.ComponentModel.Composition;
public class MyClass {
public static CompositionContainer Container = new CompositionContainer();
private void Initialize(Action<CompositonBatch> action) {}
public MyClass() {
CompositionBatch batch = null;
inititialize(x=> {
// create catalog instances: instance1 and instance2 as example
// ...
x.AddPart(instance1);
x.AddPart(instance2);
batch = x;
});
// at this point, will be batch be none-null value will parts added?
// the following code is composing batch to the container
Container.Compose(batch);
}
}
Basically, the method Initialize(Action<CompositionBatch> action) is used to initialize MEF catalog parts to a CompositionBatch instance, which adds all the import and export parts. After that, the batch is composed to the container to resolve all the DI mappings.
I am not sure if I use System.Action<T> and Lambda expression correctly here. Would x be created by Composition() CTOR on-fly in this example? Should I put anything in the method Initialize()? Or should I create a delegate as Initialize() instead(if so I think I still need to bind it to a method)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是您从未调用 lambda 表达式。为此,您需要像这样更改
Initialize()
方法:请注意现在如何实际调用传递给函数的方法。另外,您的构造函数中存在拼写错误(初始化而不是初始化),并且我没有看到
instance1
和instance2
的声明位置。但我不确定你在这里是否真的有所收获。另请注意,这将在
batch
变量上创建一个闭包。The problem here is that you never invoke your lambda expression. To do that, you need to change your
Initialize()
method like this:Note how now you actually call the method you pass to the function. Also, there's a typo in your constructor (intialize rather than Initialize) and I'm not seeing where
instance1
andinstance2
are declared.But I'm not sure you really gain anything here. Also be warned that this will create a closure over the
batch
variable.