开发者

Inheriting properties with accessibility modifier in C#

开发者 https://www.devze.com 2023-04-07 09:22 出处:网络
I tried to inherit interface, and make some of the automatically generated set property as private. This is an example.

I tried to inherit interface, and make some of the automatically generated set property as private. This is an example.

public class MyClass
{
    public interface A 
    {
        int X {get; set;}
    }
    public interface B : A
    {
        int Y {get; set;}
    }

    public class C : A
    {
        public int X {get; private set;}
    }

When I tried to compile it. I got an error 'MyClass.C' does not implement interface member 'MyClass.A.X.set'. 'MyClass.C.X.set' is not public..

I tried with private set; in iterface A, but I got this error again : 'MyClass.A.X.set': accessibility modifiers may not be used on accessors in an interface.

Is this accessibility modifier not allowed in C#开发者_如何学Go?


I tried with private set; in iterface A, but I got this error again

If your interface only requires that a property should be retrievable, you define it as:

public interface A 
{
    int X {get;}  // Leave off set entirely
}


The declaration of an interface defines the public set of members that the implementing type must have. So, if C implements A, it must have a public member for each member defined by the interface.

A defines that any implementing type must have a public property X with a public getter and a public setter. C does not meet this requirement.


You can think of an interface as the minimum functionality that your class must implement. If the interface specifies that a property exposes a get and a set clause, then you must implement a public get and set clause in your class, because only public methods and properties can implicitly implement interfaces.

You can simply leave out the set keyword in the interface property definition if you don't want to expose a public mutator. Then you can make the implementation mutator either public or private.


No it is not allowed. Remember, code which is using an instance of class C must be able to treat it as an interface A, which means that the contract is a public getter and setter for property X.

This applies to class inheritance as well as interface inheritance -- you must follow the contract of the type you are derived from.

If the intent of the code is that property X should not have a public setter, then the interface should be defined with just the { get; }


I believe interface members must be public if the interface itself is public. Your implementation of the property is faulty because of that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号