【问题标题】:A design problem about interfaces and inheritance in C#.NetC#.Net中关于接口和继承的设计问题
【发布时间】:2011-09-01 16:46:33
【问题描述】:

我很难找到下面关于继承和 OOP 的问题的答案。有人可以帮忙吗?

问题来了:

假设我在名为 KioskFramework 的程序集中有一个名为 ServiceManager 的类,它实现了两个不同的接口,分别名为 IServiceManager@ 987654324@

public interface IServiceManager
{
    string SerialNumber { get; }
    string Description { get; set; }

    int DoFoo(IServiceManager instance, int a, int b);
}

public interface IServiceProvider
{
    void DoSomethingRESTRICTED();
}

class ServiceManager : IServiceManager, IServiceProvider
{
    public void DoSomethingRESTRICTED();

    …  // some other properties and methods...

    public string SerialNumber { get { … } }

    public string Description { get { … } set { … } }

    public int DoFoo(int a, int b)
    {
       …
    }
}

我在名为KioskFramework.MonitoringService 的程序集中还有另一个名为MonitoringService 的类,它使用ServiceManager 类的某些属性(在IServiceManager 中定义的属性)。 p>

class MonitoringService
{
    …  // some other properties and methods...

    public int DoBar(IServiceManager instance, int a, int b)
    {
       // an example to show that I need access to ServiceManager's properties
       return instance.SerialNumber.Length + 
              instance.Description.Length + 
              instance.DooFoo(a, b);
    }
}

我想要做的是,我希望能够使用MonitoringService 中的某些属性,但没有其他类或程序集(例如KioskFramework.ControllingService 中的ControllingService)可以访问该属性。

class ControllingService
{
    public void DoSomethingElse(IServiceProvider instance)
    {
        // this method should not have access to the IServiceManager's 
        // properties and methods, even if it has an instance of
        // IServiceProvider, or even if it has referenced the assembly 
        // containing IServiceManager interface
    }
}

有可能吗?如何?有解决这个问题的设计模式吗?

也许我的想法有误,但我的目标是限制某个类的某些成员只能在某些程序集中看到/使用,而不是全部。

编辑:在 Mark Cidade 回答之后,我编辑了这篇文章,说我不想将“KioskFramework”程序集的其他内部成员和类暴露给“KioskFramework.MonitoringService”程序集。

提前致谢。

【问题讨论】:

  • 为什么这被否决了?
  • 如果我不想暴露所有其他内部结构怎么办?有人吗?

标签: c# oop design-patterns inheritance interface


【解决方案1】:

您可以将接口标记为internal 并将InternalsVisibleTo 属性应用于程序集:

来自 KioskFramework.dll:

[assembly:InternalsVisibleTo("KioskFramework.MonitoringService")]

【讨论】:

  • 这是我的第一个想法……不过,我希望有一种方法可以直接在界面上执行此操作。
  • 所以它们在两个不同的程序集中没关系吗?是否需要强命名“KioskFramework.MonitoringService”?让我告诉你一件事。我不希望“KioskFramework.MonitoringService”可以看到“KioskFramework”的任何其他内部类和成员。那怎么办?
  • 不必强命名。不幸的是,所有其他内部类都必须对 KioskFramework.MonitoringService 可见。您无法在此处获得更具体的信息。
  • @Mark Cidade:你确定没有解决方法或设计模式可以做到这一点吗?
  • 我认为不值得。例如,您可以使内部组件对中间组件可见,并且只从该组件中公开您想要的内容,但我认为这不是一个好主意。
【解决方案2】:

我不确定您的目标是什么 - 所以一些一般性的指示:

  • 您可以创建这些接口internal 并定义允许哪个程序集看到这些成员assembly: InternalsVisibleTo

  • 您可以创建成员protected 并通过反射访问它们

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多