【发布时间】:2010-10-31 07:06:46
【问题描述】:
一定有一些关于接口/泛型的基础知识我还没有学过。我希望现在能学会。
这是场景:
我有这个接口和类:
public interface IInterface
{
string TestValue { get; set; }
}
public class RealValue: IInterface
{
public string TestValue { get; set; }
}
如果我创建一个这样的方法,它编译得很好:
public class RandomTest: IMethodInterface
{
public IInterface GetRealValue()
{
RealValue realValue = new RealValue();
return realValue;
}
}
请注意,我正在返回一个实现接口的对象。
现在,如果我在 RandomTest 类中添加一个返回列表的方法,那么它就不再起作用了:
public List<IInterface> GetRealValues()
{
List<RealValue> realValues = new List<RealValue>();
return realValues; // ERROR Here <- says it can't convert to a List<IInterface>
}
所以,我的猜测是泛型无法解决这个问题,但为什么呢?
有没有办法解决这个问题?上面方法的返回值因为你实现这样的接口而被锁定了怎么办:
public interface IMethodInterface
{
IInterface GetRealValue();
List<IInterface> GetRealValues(); // Can't just convert the return types to a concrete
// class because I am implementing this. This
// interface is in a separate project that does not
// have the concrete classes.
}
还有希望吗?你会怎么做?
【问题讨论】: