简体   繁体   中英

Inherited a property from interface to class

interface IRestrictionUserControl
{
    public GeneralRestriction Foo{ get; protected set; }
}

public partial class RestrictionUserControl : UserControl, IRestrictionUserControl
{
    public RestrictionUserControl(Restriction r)
    {
        InitializeComponent();
        Foo = r;
    }
 }

I get the error: The name 'Foo' does not exist in the current context . What am I doing wrong?

Note: Restriction inherites from GeneralRestriction .

You have to define the implementation for Foo in the class since an interface is only defining the contract for the property. Also, you have to remove the public keyword from the interface definition since all methods/properties defined by an interface are always public.

You must Implement Foo in the derived class.

public partial class RestrictionUserControl : UserControl, IRestrictionUserControl
{
    public RestrictionUserControl(GeneralRestriction r)
    {
        InitializeComponent();
        Foo = r;
    }

    public GeneralRestriction Foo
    {
        get; protected set;
    }
}

From MSDN

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface

One more point: Interface members cannot be defined with access modifiers. So you have to change your interface declaration like this otherwise it will not even compile.

interface IRestrictionUserControl
{
    public GeneralRestriction Foo{ get; /*protected set;*/ }
}   

RestriccionUserControl = RestrictionUserControl?

I believe you have a typo

You only inherit members and methods from classes not interfaces. Interface is a template of things which it's going to force the implementing class to have.

So if your interface has a public member property, you will need to implement it in the class, just like you do with the methods.

When you write GeneralRestriction Foo{ get; protected set; } GeneralRestriction Foo{ get; protected set; } GeneralRestriction Foo{ get; protected set; } in an interface definition, it doesn't mean the same as in a class definition.

In a class the compiler will generate the getter and the setter (since C# 2.0 if I remember well), but in the interface you just say that your property must have a public getter and a protected setter.

So you have to implement them in the derived class as it was said in other answers, and by implement I mean just declare a getter and a setter (you can even copy paste the code from your interface into your class)

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