簡體   English   中英

防止在派生類C#中調用基類實現的接口方法

[英]Prevent calling base class implemented interface method in the derived class C#

是否可以在基類中實現接口,並允許在第一個派生類級別調用/覆蓋已實現的方法,但可以防止從任何其他派生類調用它?

    public interface IInterfaceSample
    {
        bool Test();
    }

    public class Base: IInterfaceSample
    {
        public virtual bool Test()
        {
             return True;
        }
    }

    public class Sub1: Base
    {
        //I need to be able to override the Test method here
        public override bool Test()
        {
             return True;
        }
    }

    //Under a separate project:
    public class Sub2: Sub1
    {
       //I need to prevent overriding the interface implementation in this class
    }

現在我需要的是:

    var b = new Base();
    b.Test();//This should work

    var s1 = new Sub1();
    s1.Test();//I need this to work too

    var s2 = new Sub2();
    s2.Test();//I need to prevent doing this

到目前為止,我認為這是不可能的,因為接口必須是公共的,否則使用接口沒有真正的價值。

在我的情況下,我需要Sub2類可以訪問Sub1中的屬性,但只能訪問該類,而不能訪問該類上的方法,特別是接口實現方法。

我能夠做到這一點的唯一方法是根本不使用接口,而是這樣做:

    public class Base
    {
        internal virtual bool Test()
        {
             return True;
        }
    }

    public class Sub1: Base
    {
        //I am able to override the Test method here
        internal override bool Test()
        {
             return True;
        }
    }

    //Under a separate project:
    public class Sub2: Sub1
    {
       //Nothing to override here which is what i need
    }

    var b = new Base();
    b.Test();//This works

    var s1 = new Sub1();
    s1.Test();//This works too

    var s2 = new Sub2();
    s2.Test();//This is prevented

但是我想知道如果接口仍然可以實現這一點,任何幫助將不勝感激。

不,這是不可能的-它將破壞多態性的整個觀點。 特別是,假設您沒有使用var ,而是顯式使用了類型:

Sub1 s2 = new Sub2();
s2.Test();

必須編譯:

  • 第一行必須編譯,因為Sub2是從Sub1派生的。
  • 第二行必須進行編譯,因為您希望s1.Test()進行編譯,其中s1的編譯時類型也為Sub1

根據經驗,如果您有X和Y兩個類,並且X上只有一些公共操作對Y有效,那么Y不應從X派生。您應該能夠處理派生類的任何實例就像它是基類的實例(及其實現的所有接口)一樣。

您希望Test方法僅在Sub1可用,但仍與Sub2共享相同的屬性。 這可以通過更改繼承鏈來實現:
在此處輸入圖片說明
對此:
在此處輸入圖片說明

在Sub1中使用sealed protected override bool Test()

暫無
暫無

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

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