【问题标题】:How to change exported property through MEF?如何通过 MEF 更改导出的属性?
【发布时间】:2013-12-28 08:03:30
【问题描述】:

我正在研究 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 类的 Text,A.Description 也可以更改。

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

【问题讨论】:

    标签: export mef


    【解决方案1】:

    这种方法适用于大多数引用类型,但不适用于不可变的字符串。这意味着你改变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 中最常见的是事件。

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2017-10-05
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2016-02-22
      • 1970-01-01
      相关资源
      最近更新 更多