C#编译器不允许以下内容。它说Cool的ICool的Jello方法的实现不会返回IObject。但是Object是一个IObject。为什么不支持?
interface ICool
{
IObject Jello();
}
interface IObject
{
}
class Cool : ICool
{
public Object Jello() { return new Object(); }
}
class Object : IObject
{
}
答案 0 :(得分:0)
以下是C#不支持返回类型协方差的解决方法(请参阅"Interface not implemented" when Returning Derived Type):
using System.Text;
using System.Threading.Tasks;
namespace CsharpFun
{
class Program
{
static void Main(string[] args)
{
Object obj = (Object) new Cool().Jello();
}
}
interface ICool<T> where T : IObject
{
T Jello();
}
interface IObject
{
}
class Cool : ICool<Object>
{
public Object Jello() { return new Object(); }
}
class Object : IObject
{
}
}