public interface IStorage<T> extends Iterable<T> {
public void copyTo( IStorage<? super T> dest);
public void copyFrom( IStorage<? extends T> src);
}
上面是我必须在c#中放进的java代码,现在它看起来像
interface IStorage<T>: IEnumerable<T>
{
void copyTo( IStorage<? super T> dest);
void copyFrom( IStorage<? extends T> src);}
但是,当它出现在函数的参数中时,我很难找到它的等价物,我找到了输入/输出,或者在哪里接近,但我仍然不清楚。
发布于 2015-04-04 13:21:00
C#中的泛型方差与.NET中的泛型差异很大。
你想要这样的东西:
public interface IStorage<out T> : IEnumerable<T>
{
// This won't compile - the constraint is on the wrong argument
void CopyTo<TDest>(IStorage<TDest> dest) where T : TDest
}
但正如所述,这是无效的。
正如所写的那样,这个方法对我来说没有什么意义--您需要接口中的其他东西来接受T
类型的值,此时IStorage
在T
中就不再是协变的了。
考虑到你不能达到完全相同的效果,我建议你考虑一下你真正想要达到的目标,并考虑这样的事情:
public interface IStorage<out T> : IEnumerable<T>
{
void AddAll(IStorage<T> source);
}
甚至只是:
public interface IStorage<out T> : IEnumerable<T>
{
void AddAll(IEnumerable<T> source);
}
因此,您可以将调用的目标从源反向到目的地,此时目标可以从源中提取值,这与IEnumerable<T>
作为值的来源更加一致。
https://stackoverflow.com/questions/29446845
复制相似问题