接口作为返回类型 [英] interface as return type
本文介绍了接口作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
接口可以是函数的返回类型。如果是,那么最大的优势。例如下面的代码是正确的返回接口数组。
Can interface be a return type of a function. If yes then whats the advantage. e.g. is the following code correct where array of interface is being returned.
public interface Interface
{
int Type { get; }
string Name { get; }
}
public override Interface[] ShowValue(int a)
{
.
.
}
推荐答案
是的,你可以返回一个界面。
Yes, you can return an interface.
我们说类 A
和 B
每个工具接口 Ic
:
Let's say classes A
and B
each implement interface Ic
:
public interface Ic
{
int Type { get; }
string Name { get; }
}
public class A : Ic
{
.
.
.
}
public class B : Ic
.
.
.
}
public Ic func(bool flag)
{
if (flag)
return new A();
return new B();
}
在此示例中 func
就像工厂方法—它可以返回不同的对象!
In this example func
is like factory method — it can return different objects!
这篇关于接口作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文