簡體   English   中英

如何在派生的 class c# 中使用接口中的受保護屬性?

[英]How to use protected property from interface in derived class c#?

如何在派生的 class c# 中使用接口中的受保護屬性?

有接口:

    interface I1
    {
        protected delegate void MoveHandler(string message);
        protected string Name => "hi";
    }
    

我嘗試從界面中獲取它:

    class A : I1
    {
        public void doWork()
        {
            I1.MoveHandler i = new I1.MoveHandler(() => { });
            // but no I1.Name
        }
    }

我嘗試從這個 class 上下文中獲取:

    class A : I1
    {
        public void doWork()
        {
            Console.WriteLine(Name);
        }
    }

但是沒有成功。 如何使用它們?

不是你的問題的答案,但它似乎有點有趣。 雖然在實現 class 時似乎不可能對受保護的成員做一些有用的事情(你也可以自己顯式地實現它,但就是這樣,你仍然不能用它做任何事情):

class A : I1
{
    public void doWork()
    {
        I1.MoveHandler i = new I1.MoveHandler((i) => { });
        // but no I1.Name
    }
    
    string I1.Name => "A";
}

您可以在派生接口中使用它:

interface I2 : I1
{
    string NameI2 => Name;
}

並且可以使用NameI2

class A2 : I2
{
}

I2 i2 = new A2();
Console.WriteLine(i2.NameI2); // prints "hi"

甚至在實現 class 時過載:

class A2 : I2
{
    string I1.Name => "InA2";
}
I2 i2 = new A2();
Console.WriteLine(i2.NameI2); // prints "InA2"

我還沒有找到很多關於含義protected的修飾符接口成員的文檔。 Roslyn github頁面上有一些關於默認接口實現的內容,但我無法破譯它)

UPD

找到了一些有用的用法——因為它可以被覆蓋,所以它可以用作某種模板模式:

interface I1
{
    public string Name { get; }
    public void SayHello() => Console.WriteLine($"{Greeting}, {Name}");
    protected string Greeting => "hi";
}

class A : I1
{
    public string Name => "Slim Shady";
    string I1.Greeting => "Yo";
}

I1 a = new A();
a.SayHello(); // prints "Yo, Slim Shady"

暫無
暫無

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

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