1

I think I have painted myself into a corner here: Lets say I have a bunch of code that I use in multiple projects, so I put that in namespace Company.

Then all project-specific code goes in Company.Project. I can then call code in the library - the outer namespace - from the project namespace without having to specify the namespace - it's implicitly imported. Fine.

However, say I have some code that I use in all the projects, but which is implemented differently project by project. For the sake of example, lets say I have a diagnostic window and code that I might implement in WPF, or Winforms, or with a different look and feel for each project. As it's implemented project by project, it can't go in the Company namespace, but when it's in the project namespace, I can only call it from the Company namespace by specifying the inner namespace - which is going to be different for each project.

I guess I could use delegates to solve this but it seems messy - is there an easier way?

4

2 回答 2

4

也许使用接口?在命名空间中定义接口Company。然后让每个项目实现接口。然后使用Company命名空间中的接口。

这种方法的一个缺点是仍然需要在某个地方创建一个类来创建接口实现的项目特定实例。就像某种工厂一样,它需要同时引用Company命名空间和实现它的项目特定类。

于 2013-09-23T19:02:53.277 回答
1

听起来你需要某种 IoC 并使用接口来解决这个问题。这是一个没有任何特殊库的简单程序:

// In your shared project
namespace Company {
    public interface IDiagnosticWindow {
        void ShowMessage(string message);
    }

    public static class Utilities {

        private static IDiagnosticWindow _diagnosticWindow;

        public static void InitializeDiagnosticWindow(IDiagnosticWindow dw) {
            _diagnosticWindow = dw;
        }

        public static void ShowMessage(string message) {
            _diagnosticWindow.ShowMessage(message);
        }
    }
}

// In your WinForms project
namespace Company.WinForms {
    public class WinFormsDiagnosticWindow : IDiagnosticWindow {
        public void ShowMessage(string message) {
            MessageBox.Show(message);
        }
    }

    static void Main() {
        Utilities.InitializeDiagnosticWindow(new WinFormsDiagnosticWindow());
    }
}

为每个其他应用程序类似地实现它。在此示例中,在应用程序启动时手动初始化它很重要。但是如果您在 中执行此操作Main,那么它将被初始化,并且Utilities.ShowMessage可以在核心项目或您的应用程序项目中使用。

像 Ninject 这样的库也可以通过更好地连接这种关系来帮助你。

于 2013-09-23T19:09:24.697 回答