简体   繁体   English

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

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

How to use protected property from interface in derived class c#?如何在派生的 class c# 中使用接口中的受保护属性?

There is interface:有接口:

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

I tried take it from interface:我尝试从界面中获取它:

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

I tried take from this class context:我尝试从这个 class 上下文中获取:

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

But there is no success.但是没有成功。 How to use them?如何使用它们?

Not an answer to your question, but it seems kind of interesting.不是你的问题的答案,但它似乎有点有趣。 While it seems impossible to do something useful with protected member in implementing class (also you can explicitly implement it yourself, but that's it, you still can't do anything with it):虽然在实现 class 时似乎不可能对受保护的成员做一些有用的事情(你也可以自己显式地实现它,但就是这样,你仍然不能用它做任何事情):

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

You can use it in derived interface:您可以在派生接口中使用它:

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

And the NameI2 can be used:并且可以使用NameI2

class A2 : I2
{
}

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

Or even overloaded in implementing class:甚至在实现 class 时过载:

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

I have not found a lot of documentation about meaning protected modifier interface members.我还没有找到很多关于含义protected的修饰符接口成员的文档。 There is some on Roslyn github page about default interface implementation, but I was not ale to decipher it) Roslyn github页面上有一些关于默认接口实现的内容,但我无法破译它)

UPD UPD

Found some kind of useful usage - since it can be overridden, it can be used as some kind of template pattern:找到了一些有用的用法——因为它可以被覆盖,所以它可以用作某种模板模式:

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