簡體   English   中英

如何從 C# 中的接口隱藏已實現屬性的設置方法?

[英]How to hide set method of an implemented property from an interface in C#?

大家好...

如果我有以下界面:

interface IMyInterface
{
    int property { get; set; }
}

以及以下實現:

class MyClass : IMyInterface
{
// anything
}

如何從MyClass的實例中隱藏屬性的set方法...換句話說,我不希望propertyset方法是公共的,這可能嗎?

抽象 class 很容易做到:

abstract class IMyInterface
{
    int property { get; protected set; }
}

然后我只能在實現上述抽象 class 的 class 中set property ...

開始時界面中沒有set 您仍然可以將其實現為private

你不能“隱藏”它,它是合同的一部分。 如果您不希望它成為合同的一部分,請不要定義它。

如果某些實現只實現接口的某些部分,則最好將接口細分為每個實現將完全實現或根本不實現的部分,然后定義繼承它們所有常見組合的接口。 調整你的例子:

interface IMyReadableInterface
{
    int property { get; }
}
interface IMyFullInterface : IMyReadableInterface
{
    new int property { get; set; }
}

想要支持讀寫訪問的類應該實現 IMyFullInterface; 那些只想支持讀取訪問的人應該只實現 IMyReadableInterface。 對於使用 C# 編寫並隱式實現property的任一接口的實現,這種隔離不需要任何額外的工作。 在 VB 中實現property的代碼,或在 C# 中顯式實現property的代碼,將必須定義property的兩種實現——一種只讀和一種讀寫,但這就是生活。 properties (I really don't understand why C# can't use a read-only and write-only property together as thought they were a read-write property, but it can't).請注意,雖然可以定義一個只有一個 setter 的IMyWritableInterface ,並且讓IMyFullInterface繼承IMyReadableInterfaceIMyWritableInterfaceIMyFullInterface仍然必須定義自己的讀寫屬性,並且在使用顯式實現時必須定義屬性(我真的不明白為什么 C# 不能一起使用只讀和只寫屬性,因為它們認為它們是讀寫屬性,但它不能)。

如果您使用以下接口,則當通過該接口操作類時,set 方法將不可用:

interface IMyInterface
{ 
   int property { get; }
}

然后,您可以像這樣實現 class:

class MyClass : IMyInterface
{
  int property { get; protected set; }
}

假設您需要 setter 作為接口的一部分,但由於某種原因,在特定實現者(在本例中為 MyClass)上使用它沒有意義,您總是可以在 setter 中拋出異常(例如 InvalidOperationException) . 這不會在編譯時保護您,只會在運行時保護您。 但這有點奇怪,因為在接口上運行的代碼不知道是否允許調用 setter。

在某些情況下,您希望接口有一個set ,然后將其隱藏在一些具體的 class 中。

我相信下面的代碼顯示了我們想要完成的事情。 即實現隱藏了setter,但任何IMyInterface感知組件都可以訪問它。

public static void Main()
{
    var myClass = new MyClass();
    myClass.Property = 123;                 // Error
    ((IMyInterface)myClass).Property = 123; // OK
}

它基本上與您在IDisposable.Dispose()中經常看到的模式相同,其中您有一個Explicit Interface Implementation 這是完整性的示例。

public interface IMyInterface
{
    int Property { get; set; }
}

public class MyClass : IMyInterface, IDisposable
{
    public int Property { get; private set; }

    int IMyInterface.Property
    {
        get => Property;
        set => Property = value;
    }
    
    void IDisposable.Dispose() {}
}

打字太多:(

C#在這里對我們沒有多大幫助。 理想情況下,設置器可以有一個顯式的接口實現:

// In C# 10 maybe we can do this instead:
public class MyFutureClass : IMyInterface
{
    public int Property { get; IMyInterface.set; }
}

請參閱此處C#功能建議。

接口中沒有受保護或私有的,一切都是公共的。 您要么不定義任何集合,要么將其用作公共。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM