![](/img/trans.png)
[英]How to access Interface method implemented in the derived class from child class?
[英]How can i call method from class but this method implemented from any interface?
我试图打电话给base.Alan(); 在HacimBul。 但是基础。 不要给出智能的alan方法
public double HacimBul()
{
throw new Exception();
//return base..... --> how can i see base.Alan();
}
namespace interfaceClass
{
class Program
{
static void Main(string[] args)
{
}
}
interface Ikenar
{
double kenar { get; set; }
}
interface Iyukseklik
{
double yuksekli {get; set;}
}
interface IAlan
{
double Alan();
}
interface IHacim
{
double Hacim();
}
class Alan : Ikenar, IAlan
{
public double kenar
{
get;
set;
}
double IAlan.Alan()
{
return kenar * kenar;
}
}
class Hacim : Alan, Iyukseklik
{
public double kenar
{
get;
set;
}
public double yuksekli
{
get;
set;
}
public double HacimBul()
{
throw new Exception();
//return base..... --> how can i see base.Alan();
}
}
}
不,目前暂时无法使用。 由于显式接口实现,因此基本实现仅在IAlan
类型的表达式上可用。
您可以使用此:
return ((IAlan)this).Alan();
或者,您可以改用Alan
隐式接口实现,尽管这将意味着重命名类或方法。
对于其他试图解决这个问题的人,它更简单地表示为这种方式-不会将方法名重用为类名:
public interface IFoo
{
void Bar();
}
public class BaseFoo : IFoo
{
void IFoo.Bar()
{
// Do something
}
}
public class DerivedFoo : BaseFoo
{
void OtherMethod()
{
// Doesn't compile due to explicit interface implementation
base.Bar();
// Will work
((IFoo)this).Bar();
}
}
该方法不是公共的或受保护的,它是您定义方法的私有方法,甚至比私有方法还要private
,仅当您通过接口时才可用。
这意味着要调用该方法,您必须:
在Alan中将Alan方法的显式实现更改为隐式实现(将方法公开):
public void Alan() { }
或者,您将必须在调用期间强制转换实例:
((IAlan)this).Alan();
不幸的是,使用最后一种语法,您实际上将不会调用“ base.Alan”,而只是调用“ this.Alan”,如果您在后代类中重写该方法,则可能会有所不同。
这是一个例子:
using System;
namespace interfaceClass
{
public interface ITest
{
void Execute();
}
public class Base : ITest
{
void ITest.Execute()
{
Console.Out.WriteLine("Base.ITest.Execute");
}
}
public class Descendant : Base, ITest
{
void ITest.Execute()
{
Console.Out.WriteLine("Descendant.ITest.Execute");
}
public void Test()
{
// There's no way to call "base.Execute()" here
((ITest)this).Execute();
}
}
class Program
{
static void Main(string[] args)
{
Descendant d = new Descendant();
d.Test();
}
}
}
double IAlan.Alan() // this is explicit interface implementation
{
return kenar * kenar;
}
通过在方法名称前加上接口前缀,您就是在告诉用户方法Alan
仅可通过接口而不是类的引用来使用。
将以上更改为
double Alan()
{
return kenar * kenar;
}
在Alan
班里面。
您已经对Alan进行了明确的实现,因此您必须选择
要么更改方法的名称,要么更改名为Alan的类的名称,这样就不会出现名称冲突并将该方法实现为常规方法了。
public double Alan() //name of class can't be Alan in this case
{
return kenar * kenar;
}
要么
public double HacimBul()
{
return ((IAlan)this).Alan();
}
您无法获得智能感知的原因是该方法仅在将Alan类型的对象声明为IAlan时才可用,否则Alan方法将被隐藏
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.