gpt4 book ai didi

C#/MEF 不适用于没有无参数构造函数的基类

转载 作者:太空狗 更新时间:2023-10-29 22:33:47 25 4
gpt4 key购买 nike

我有一个 Prim 类,它实现了 MEF 的 IPrimitiveDecomposer 接口(interface)并继承了 Node 基类。

public class Node
{
public Node()
{
}
}

public interface IPrimitiveDecomposer
{
bool Match(Node node);
}

[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
public bool Match(Node node) {return true;}
}

但是,当我继承一个没有无参数构造函数的类时,MEF 的 ComposeParts() 方法无法导入 Prim 对象。我在 this page in MSDN 之后添加了 ImportingConstructor 的属性,因为我在没有该属性的情况下遇到编译错误。

[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
[ImportingConstructor]
public Prim(int val) : base (val)
{}

public bool Match(Node node) {return true;}
}

不起作用的代码如下。当您为 Node 类提供无参数构造函数时,它就起作用了。

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

public class Node
{
public Node(int val)
{
}
}

public interface IPrimitiveDecomposer
{
bool Match(Node node);
}

[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
[ImportingConstructor]
public Prim(int val) : base (val)
{}

public bool Match(Node node) {return true;}
}

public class Test
{
[ImportMany(typeof(IPrimitiveDecomposer), AllowRecomposition = true)]
private IEnumerable<IPrimitiveDecomposer> PrimitiveDecomposers { get; set; }

void mef()
{
// MEF
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}

static void Main()
{
var mef = new Test();
mef.mef();
var res = mef.PrimitiveDecomposers;

foreach(var it in res)
{
Console.WriteLine(it);
}
}
}

最佳答案

只有当构造函数的参数是 MEF 导出对象时,ImportingConstructor 属性才有效。 Prim(int val) 构造函数组合失败,因为 MEF 不知道为构造函数提供什么值。

这个特定场景看起来更适合 MEF 工厂模式。

interface IPrimitiveDecomposerFactory {
IPrimitiveDecomposer Create(int value);
}

[Export(typeof(IPrimitiveDecomposerFactory))]
sealed class PrimitiveDecomposerFactor : IPrimitiveDecomposerFactory {
public IPrimitiveDecomposer Create(int value) {
return new Prim(value);
}
}

现在代码可以导入 IPrimitiveDecomposerFactory 并使用它根据特定的 int 值创建 IPrimitiveDecomposer 实例

关于C#/MEF 不适用于没有无参数构造函数的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9023098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com