[英]Access modifiers nbot permitted when provided explicit implementation for interface member in imlementing class C#
interface honda {
void meth();
protected void meth2();
}
class crv : honda {
void honda.meth() { } //public not allowed
void honda.meth2() { } //protected not allowed
}
I gave interface honda
that has 2 abstract methods:我给了具有 2 个抽象方法的接口
honda
:
meth();方法(); which is public
这是公开的
meth2(); meth2(); which is protected
受保护的
Whay do I get an error when i say public void honda.meth(){}
or protected honda.meth2() { }
in the implementing class crv
?当我在实施 class
crv
中说public void honda.meth(){}
或protected honda.meth2() { }
时,为什么会出现错误?
I mean i have one assumption: It is beacuse by doing this, we provide default implementation for the method, so It is like in the interface but It is not.我的意思是我有一个假设:这样做是因为我们为该方法提供了默认实现,所以它就像在接口中,但它不是。 This assumption wpuld justify the error when I say
public void honda.meth(){}
but it does not justify the error whjen I try to say protected honda.meth2() { }
since the meth2()
is protected in the interface.当我说
public void honda.meth(){}
时,这个假设证明了错误是合理的,但是当我尝试说protected honda.meth2() { }
时,它不能证明错误是合理的,因为meth2()
在接口中受到保护。
Could you please help me?请你帮助我好吗?
By declaring the methods in the implementing class as honda.meth
, this is an explicit interface implementation .通过将实现 class 中的方法声明为
honda.meth
,这是一个显式接口实现。 Basically, it means that these methods can only be called on an object of type honda
, not crv
so the access modifiers on crv
are never going to be used.基本上,这意味着这些方法只能在类型为
honda
的 object 上调用,而不能在crv
上调用,因此永远不会使用crv
上的访问修饰符。
If you wanted to be able to call these methods on types of both honda
and crv
, simply drop the honda.
如果您希望能够在
honda
和crv
类型上调用这些方法,只需删除honda.
prefix from the method name in the implementing class like so:实现 class 中方法名称的前缀,如下所示:
interface honda {
void meth();
void meth2();
}
class crv : honda {
public void meth() { }
public void meth2() { }
}
Note that you can't specify an access modifier in an interface ( public
, protected
etc.) unless you are using the default implementations in interfaces C# feature.请注意,除非您在接口 C# 功能中使用默认实现,否则您不能在接口(
public
、 protected
等)中指定访问修饰符。
If meth2
had to be protected, change honda
to be an abstract class and meth2
to be an abstract method:如果必须保护
meth2
,请将honda
更改为抽象 class 并将meth2
更改为抽象方法:
public abstract class honda {
public abstract void meth();
protected abstract void meth2();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.