2013-03-27 81 views
0

编辑: 也许这是一个更清晰,更对这个问题的角度制定:差异在返回类型

在一些通用接口IInterface<T>,我想回到一个泛型类型的对象,其中一个的类型参数应该是IInterface<T>的实现。

public class OtherType<T> {} 
public interface IInterface<T> 
{ 
    OtherType<IInterface<T>> Operation(); 
} 
public class Impl : IInterface<int> 
{ 
    public OtherType<IInterface<int>> Operation() 
    { 
     return new OtherType<Impl>(); 
    } 
} 

由于Impl工具IInterface<int>,它似乎是合理的,我认为我可以使用这种方式。然而,似乎我不能,我得到的编译器错误

无法转换表达式类型OtherType<Impl>到返回式OtherType<IInterface<int>>

+0

请问您能否将您非常漫长而令人困惑的类名转换为A,B,C等类似的东西? – Sebastian 2013-03-27 08:39:14

+0

@CarlPett:你是否一直关注Eric Lippert在Monads上的精彩博客系列? http://ericlippert.com/2013/02/21/monads-part-one/看来你正在努力重新发明这个构造,并且可以对一般机制有所了解。 – 2013-03-27 08:55:16

+0

@PieterGeerkens:我没有,谢谢你的提示!看起来很有趣。我只有时间阅读前四部分,但到目前为止,我真的不知道如何在这里应用它? – carlpett 2013-03-27 16:37:17

回答

1

问题是OtherType<T>是一类和一般类不允许在C#中CO /逆变。一般interfaces这样做,只要out类型不出现在任何输入位置,并且in类型不出现在任何输出位置。在你的代码示例中,你可以通过引入一个标记为covariant的附加接口来获得它,然后改变你的返回类型。

public interface IOtherType<out T> {} // new 
public class OtherType<T> : IOtherType<T> { } 

public interface IInterface<T> 
{ 
    IOtherType<IInterface<T>> Operation(); // altered 
} 
public class Impl : IInterface<int> 
{ 
    public IOtherType<IInterface<int>> Operation() 
    { 
     return new OtherType<Impl>(); 
    } 
} 

不管这实际上与你的其他方法定义适合你的使用情况的东西只有自己知道,在有限的关于您的代码段的细节。

+0

谢谢,我会试试看。虽然有趣的是“有限的细节”,但是......我的第一个表述包含了我正在使用的具体类型的细节,然后我因为有太多不相关的上下文而遭到了打击:P – carlpett 2013-03-27 18:51:08

+0

按照我的意愿工作,完美! – carlpett 2013-03-28 07:35:53

1

OtherType<IInterface<int>>并不意味着“工具” - 它有点意思“是用泛型类型参数Interface<int>OtherType,但是这不是你怎么说

如果你只是想确保返回类型实现IInterface<int>然后设置为返回类型:

public interface IInterface<T> 
{ 
    IInterface<T> Operation(); 
} 

public class Impl : IInterface<int> 
{ 
    public <IInterface<int>> Operation() 
    { 
     return new OtherType(); 
    } 
} 

其中

public class OtherType : IInterface<int> 
{} 

这意味着你可以返回一个实现IInterface<int>任何类型。

否则,你可以把它多一点约束上调用使用泛型类型约束:

public interface IInterface<T> 
{ 
    TRet Operation<TRet>() where TRet : IInterface<T>; 
} 

public class Impl : IInterface<int> 
{ 
    public TRet Operation<TRet>() where TRet : IInterface<int> 
    { 
     return new OtherType(); 
    } 
} 

这意味着你可以约束操作返回一个特定的类,它反过来又实现IInterface<int>

它会被称为:

Impl i = new Impl(); 
OtherType x = i.Operation<OtherType>();