[英]How to call an interface in C#
interface ISample
{
int fncAdd();
}
class ibaseclass
{
public int intF = 0, intS = 0;
int Add()
{
return intF + intS;
}
}
class iChild : ibaseclass, ISample
{
int fncAdd()
{
int intTot = 0;
ibaseclass obj = new ibaseclass();
intTot = obj.intF;
return intTot;
}
}
I want to call ISample
in static void Main(string[] args)
but I dont know how to do that. 我想在
static void Main(string[] args)
调用ISample
,但我不知道该怎么做。 Could you please tell me how? 你能告诉我怎么样吗?
An interface cannot be instantiated by itself. 接口不能自己实例化。 You can't just call an interface.
你不能只是调用一个接口。 You need to instantiate a class that actually implements the interface.
您需要实例化一个实际实现该接口的类。
Interfaces don't and can't do anything by themselves. 接口不能也不能自己做任何事情。
For example: 例如:
ISample instance = new iChild(); // iChild implements ISample
instance.fncAdd();
The following questions provide more detailed answers about this: 以下问题提供了有关此问题的更详细答案:
You can't "call" interface or create instance of it. 你不能“调用”界面或创建它的实例。
What you can do is have your class implement the interface then use its method fncAdd
. 你可以做的是让你的类实现接口然后使用它的方法
fncAdd
。
Do you mean?: 你的意思是?:
static void Main(string[] args)
{
ISample child = new iChild();
child.fncAdd();
}
Although, as stated by others the code doesn't seem like it's using inheritance correctly. 虽然,正如其他人所说,代码似乎并没有正确使用继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.