C# 接口作为返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15392224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
interface as return type
提问by saam
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)
{
.
.
}
采纳答案by One Man Crew
Yes, you can return an interface.
是的,您可以返回一个接口。
Let's say classes A
and B
each implement interface Ic
:
假设类A
和B
每个实现接口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();
}
In this example func
is like factory method — it can return different objects!
在这个例子func
中就像工厂方法——它可以返回不同的对象!
回答by Sten Petrov
Yes it can.
是的,它可以。
The benefit is that you can abstract the return (and input) types.
好处是您可以抽象返回(和输入)类型。
public interface IFruit{ }
public class Apple: IFruit{}
public class Pear: IFruit{}
...
public function IFruit SelectRandomFromBasket(Basket<IFruit> basket){
// this function can return Apple, Pear
}
回答by ken2k
Yes it's possible, and it's a good thing for public functions.
是的,这是可能的,这对公共职能来说是一件好事。
For the whypart of your question, I won't copy paste other people answers, so please refer to existing answers, for example:
对于你问题的为什么部分,我不会复制粘贴其他人的答案,所以请参考现有答案,例如:
回答by Mike Perrenoud
Yes an interface
is a very valid return value. Remember, you're not returning the definition of the interface, but rather an instanceof that interface.
是的 aninterface
是一个非常有效的返回值。请记住,您返回的不是接口的定义,而是该接口的实例。
The benefit is very clear, consider the following code:
好处很明显,考虑下面的代码:
public interface ICar
{
string Make { get; }
}
public class Malibu : ICar
{
public string Make { get { return "Chevrolet"; } }
}
public class Mustang : ICar
{
public string Make { get { return "Ford"; } }
}
now you could return a number of different ICar
instances that have their own respective values.
现在您可以返回许多ICar
具有各自值的不同实例。
But, the primary reason for using interfaces is so that they can be shared amongst assemblies in a well-known contract so that when you pass somebody an ICar
, they don't know anything about it, but they know it has a Make
. Further, they can't execute anything against it except the public interface. So if Mustang
had a public
member named Model
they couldn't get to that unless it was in the interface.
但是,使用接口的主要原因是它们可以在众所周知的合同中的程序集之间共享,这样当你传递给某人时ICar
,他们对它一无所知,但他们知道它有一个Make
. 此外,除了公共接口之外,他们无法对其执行任何操作。因此,如果Mustang
有一个public
名为的成员Model
,除非它在界面中,否则他们无法获得该成员。