Skip to main content
 首页 » 编程设计

C#如何解决EditorAttribute使用引起的循环依赖

2024年02月23日14sharpest

在我的项目中,我有两个库,它们目前会导致我无法解决的循环依赖。

一个库为整个解决方案提供通用数据结构。该库包含与此类似的结构:

namespace Common { 
  public class Foo { 
    //[Editor( typeof( UserEditor ), typeof( UITypeEditor ) )] 
    public UInt32 OwnerId { get; set; } 
  } 
 
  public class User { 
    public UInt32 Id { get; set; } 
  } 
} 

现在在我们解决方案的一个项目中,我们想通过 PropertyGrid 编辑 Foo 实例,并且应该使用自定义编辑器编辑 OwnerId 属性;这个:

using Common; 
 
namespace Common.Gui { 
  public class OwnerEditor : UITypeEditor { 
    public static List<User> Users { get; set; } 
  } 
} 

现在,我不能只将 EditorAttribute 添加到 Foo.OwnerId,因为那样会产生循环依赖,我想保留对 Common 的引用.Gui 从 Common 无论如何。我还想避免将代码从 Common 中提取到一个新程序集中,因为许多其他项目都引用了它。

我发现了一个关于 adding EditorAttribute at runtime 的问题,这听起来像是一个完美的解决方案,但我无法用它来解决我的问题。

请您参考如下方法:

我认为这是设计缺陷的标志。您是否希望编辑 GUI 不知道包含 Foo 的类库?在这种情况下,它不应包含 EditorAttribute。

一种解决方案是将 Foo 类视为 MVVM 架构中的模型。然后,您可以在应用 EditorAttribute 的 GUI 类库中创建一个包装 ViewModel。如果你提取一个接口(interface) IFoo,我将它放在你的模型类库中,你可以使用装饰器模式。