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

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

我得到错误:The name 'Foo' does not exist in the current context。我究竟做错了什么?

注意:Restriction继承自GeneralRestriction.

4

5 回答 5

4

您必须在类中定义 Foo 的实现,因为接口仅定义属性的合同。此外,您必须从接口定义中删除 public 关键字,因为接口定义的所有方法/属性始终是公共的。

于 2013-03-30T17:48:08.243 回答
3

您必须在派生类中实现Foo。

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

    public GeneralRestriction Foo
    {
        get; protected set;
    }
}

来自MSDN

接口包含方法、委托或事件的签名。方法的实现在实现接口的类中完成

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;*/ }
}   
于 2013-03-30T17:48:43.870 回答
1

RestrictionUserControl = RestrictionUserControl?

我相信你有一个错字

于 2013-03-30T17:47:18.003 回答
1

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.

于 2013-03-30T17:51:34.653 回答
0

When you write 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)

于 2013-03-30T17:53:50.533 回答