如何隐藏实现

Che*_*tah 6 c# oop

假设我有一个类库,其中任何内部类都可以访问以下接口:

interface myInterface
{
    string myProperty { get; set; } // notice setter.
}
Run Code Online (Sandbox Code Playgroud)

但是如果有人将这个类库添加到他们的项目中,他们会得到以下接口:

public interface myInterface
{
    string myProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

这样做最有效和最受欢迎的方式是什么?有一个接口实现另一个?

And*_*tan 0

我认为@adrianbanks的答案可能是对我的一个改进,但我不认为它真的是(尽管很漂亮) - 因为你不能保证传递给你的公共接口实例也实现了内部接口实例 - 这该解决方案也是如此。还有一点是,它仅在实现类型是的情况下才有效internal- 如果您想提供公共类型作为标准接口实现或作为层次结构的基础,那么这是不好的。

这就是我用的。鉴于:

interface myInterface
{
  string myProperty { get; set; }
}

public interface myPublicInterface
{
  string myProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

首先,您不能继承myPublicInterfacemyInterface因为编译器会抱怨可访问性不一致。因此,您可以使用属性支持者显式实现内部的,然后隐式实现公共的:

public class MyClass : myInterface, myPublicInterface
{
    private string _myProperty;

    string myInterface.myProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }

    public string myProperty
    {
        get { return _myProperty; }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意 - 在某些情况下,getter 可能不适合私人支持者,但可能是一些从其他属性计算值的逻辑。在这种情况下 - 为了保持干燥 - 您可以将逻辑放在公共 getter 中,并将其用于显式 getter:

string myInterface.myProperty
{
  get { return MyProperty; }
  set { /*whatever logic you need to set the value*/ }
}

public string myProperty
{
  get { /*whatever complex logic is used to get the value*/ }
}
Run Code Online (Sandbox Code Playgroud)

你也可以用相反的方式来做,但是你必须对内部接口进行一个看起来很糟糕的内联转换:

string myInterface.myProperty
{
  get { /*whatever complex logic is used to get the value*/ }
  set { /*whatever logic you need to set the value*/ }
}

public string myProperty
{
  get { return ((myInterface)this).myProperty; }
}
Run Code Online (Sandbox Code Playgroud)

您应该尽可能避免这种情况。