简体   繁体   中英

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

How to use protected property from interface in derived 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 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 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:

class A2 : I2
{
}

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

Or even overloaded in implementing 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. There is some on Roslyn github page about default interface implementation, but I was not ale to decipher it)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM