gpt4 book ai didi

java - 从java到c#的转换——协变和逆变

转载 作者:太空宇宙 更新时间:2023-11-03 20:00:05 25 4
gpt4 key购买 nike

  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);}

但是当它出现在函数的参数中时,我很难找到等效项,我找到了 in/out 或 where 方法,但我仍然不清楚。

最佳答案

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
}

但如前所述,这是无效的。

如所写,该方法对我来说并没有真正的意义 - 你需要在接口(interface)中添加一些其他的东西来接受 T 类型的值。 ,此时IStorageT 中不再是协变的无论如何。

鉴于您无法实现完全相同的效果,我建议您考虑一下您真正想要实现的目标,并考虑类似的事情:

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>成为值(value)的源泉。

关于java - 从java到c#的转换——协变和逆变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29446845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com