如何通过MEF更改出口物业?

时间:2013-12-28 08:03:31

标签: export mef

我正在研究MEF,并尝试使用Export属性导出属性,并将其导入到其他类中。 但我的问题是我想要更改此属性,而另一个类可以导入新值。 例如,

[Export]
public class A{
    [Import("Notes")]
    public string Description{get;set;}
}

[Export]
public class B{
    [Export("Notes")]
    public string Text{get;set;}
}

我希望一旦我改变了B类的文本,A.Description也会被改变。

那么,我该如何实现呢? 有什么好主意吗?

1 个答案:

答案 0 :(得分:0)

这种方法适用于大多数引用类型,但不适用于不可变的字符串。这意味着在更改B.Text的值后,A.Description和B.Text引用的对象将不再相同(您可以使用Object.ReferenceEquals来测试它。)

使用MEF后,您要做的就是导出/导入方法而不是属性:

[Export]
public class A
{
    public string Description { get { return GetDescription(); } }        

    [Import("GetNotes")]
    Func<string> GetDescription;
}

[Export]
public class B
{        
    public string Text { get; set; }

    [Export("GetNotes")]
    string GetText()
    {
        return Text;
    }
}

最后请注意,还有其他方法可以做到这一点。 .NET中最常见的是事件。

相关问题