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
。
答案 0 :(得分:4)
您必须在类中定义Foo的实现,因为接口仅定义属性的合同。此外,您必须从接口定义中删除public关键字,因为接口定义的所有方法/属性始终是公共的。
答案 1 :(得分:3)
您必须在派生类中实施 Foo。
public partial class RestrictionUserControl : UserControl, IRestrictionUserControl
{
public RestrictionUserControl(GeneralRestriction r)
{
InitializeComponent();
Foo = r;
}
public GeneralRestriction Foo
{
get; protected set;
}
}
来自MSDN
界面包含仅方法,委托或事件的签名。方法的实现在实现接口
的类中完成
还有一点:无法使用访问修饰符定义接口成员。所以你必须像这样改变你的接口声明,否则它甚至都不会编译。
interface IRestrictionUserControl
{
public GeneralRestriction Foo{ get; /*protected set;*/ }
}
答案 2 :(得分:1)
RestriccionUserControl = RestrictionUserControl?
我相信你有一个错字
答案 3 :(得分:1)
您只从类而不是接口继承成员和方法。接口是一个模板,它将强制实现类具有。
因此,如果您的接口具有公共成员属性,则需要在类中实现它,就像使用方法一样。
答案 4 :(得分:0)
在接口定义中编写GeneralRestriction Foo{ get; protected set; }
时,它与类定义中的含义不同。
在类中,编译器将生成getter和setter(如果我记得很清楚,那么就是C#2.0),但是在界面中你只要说你的属性必须有一个公共getter和一个受保护的setter。
所以你必须在派生类中实现它们,就像在其他答案中所说的那样,并且通过实现我只是声明一个getter和一个setter(你甚至可以将代码从你的接口粘贴到你的类中)