C# 我如何从类调用方法,但该方法是从任何接口实现的?
我试着打电话给基地;在哈辛布尔。但这是基础。不要给智能感知方法C# 我如何从类调用方法,但该方法是从任何接口实现的?,c#,.net,visual-studio,oop,C#,.net,Visual Studio,Oop,我试着打电话给基地;在哈辛布尔。但这是基础。不要给智能感知方法 public double HacimBul() { throw new Exception(); //return base..... --> how can i see base.Alan(); } 通过在接口前面加上方法名,您告诉用户方法Alan只能通过接口引用使用,而不能通过类引用使用 将上述内容更改为 double Alan() {
public double HacimBul()
{
throw new Exception();
//return base..... --> how can i see base.Alan();
}
通过在接口前面加上方法名,您告诉用户方法Alan
只能通过接口引用使用,而不能通过类引用使用
将上述内容更改为
double Alan()
{
return kenar * kenar;
}
艾伦课内。不,现在不行。由于显式接口实现,基本实现仅在类型为
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();
}
}
您已经明确实现了Alan,因此您必须选择 要么更改方法的名称,要么更改名为Alan的类,这样就不会有名称冲突,并将该方法作为普通方法实现,例如
public double Alan() //name of class can't be Alan in this case
{
return kenar * kenar;
}
或
您无法获得intellisense的原因是,只有当Alan类型的obejct声明为IAlan时,该方法才可用,否则Alan方法将被隐藏该方法不是公共的或受保护的,它按照您定义的方式是私有的,甚至比
私有
更私有,只有通过该界面,它才可用
这意味着为了调用该方法,您必须:
- 将Alan方法的显式实现更改为Alan中的隐式实现(公开该方法):
- 或者,您必须在调用期间强制转换实例:
((IAlan)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();
}
}
}
我不明白你有什么问题。你为什么不接受答案呢?那是行不通的,因为这个类现在是私有的,因此派生类无法访问它。如果它是公共的,而不是私有的,那么它会起作用。。。但他还需要重命名该类,因为它与该方法具有相同的名称。尽管如此,它还是值得重新命名…@我自己,它应该说这个方法现在是私有的。谢谢拉塞·V·卡尔森。我怎样才能见到你:我的msn:yusufkaratoprak@yahoo.com请添加我:)此((IAlan)中基类的潜在重写方法存在问题。可以使用((IAlan)base避免Alan。Alan:)否,如果尝试,将出现此编译器错误:“在此上下文中使用关键字“base”无效”。我想您在发布建议之前确实尝试过吗?@Phsika,我的MSN地址已发布在我的个人资料中,但我建议您继续在堆栈溢出上发布问题,除非您对该特定答案有疑问,并且该问题与特定解决方案相关,因此其他人对此不感兴趣,但在这种情况下,我建议你使用我的电子邮件地址(与MSN地址相同,仍然张贴在我的个人资料中)
public double HacimBul()
{
return ((IAlan)this).Alan();
}
public void Alan()
{
}
((IAlan)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();
}
}
}