问题
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)
{
.
.
}
回答1:
Yes, you can return an interface.
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();
}
In this example func is like factory method — it can return different objects!
回答2:
Yes an interface is a very valid return value. Remember, you're not returning the definition of the interface, but rather an instance of that interface.
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.
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.
回答3:
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
}
回答4:
Yes it's possible, and it's a good thing for public functions.
For the why part of your question, I won't copy paste other people answers, so please refer to existing answers, for example:
- List<T> or IList<T>
- Method return an interface
- https://stackoverflow.com/a/3564291/870604
来源:https://stackoverflow.com/questions/15392224/interface-as-return-type