gpt4 book ai didi

c# - C# 泛型中的通配符等价物

转载 作者:可可西里 更新时间:2023-11-01 02:58:34 26 4
gpt4 key购买 nike

假设我有一个通用类如下:

public class GeneralPropertyMap<T>
{
}

在其他一些类中,我有一个接受 GeneralPropertyMap<T> 数组的方法.在 Java 中,为了接收包含任何类型 GeneralPropertyMap 的数组该方法看起来像这样:

private void TakeGeneralPropertyMap(GeneralPropertyMap<?>[] maps)
{
}

我们使用通配符以便稍后我们可以调用 TakeGeneralPropertyMap路过一堆 GeneralPropertyMap与任何类型 T每个,像这样:

GeneralPropertyMap<?>[] maps = new GeneralPropertyMap<?>[3];
maps[0] = new GeneralPropertyMap<String>();
maps[1] = new GeneralPropertyMap<Integer>();
maps[2] = new GeneralPropertyMap<Double>();
//And finally pass the array in.
TakeGeneralPropertyMap(maps);

我试图找出 C# 中的等效项,但没有成功。有什么想法吗?

最佳答案

C# 中的泛型比 Java 中的泛型提供更强的保证。因此,要在 C# 中执行您想要的操作,您必须让 GeneralPropertyMap<T>类继承自该类(或接口(interface))的非泛型版本。

public class GeneralPropertyMap<T> : GeneralPropertyMap
{
}

public class GeneralPropertyMap
{
// Only you can implement it:
internal GeneralPropertyMap() { }
}

现在您可以:

private void TakeGeneralPropertyMap(GeneralPropertyMap[] maps)
{
}

和:

GeneralPropertyMap[] maps = new GeneralPropertyMap[3];
maps[0] = new GeneralPropertyMap<String>();
maps[1] = new GeneralPropertyMap<Integer>();
maps[2] = new GeneralPropertyMap<Double>();
TakeGeneralPropertyMap(maps);

关于c# - C# 泛型中的通配符等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15574977/

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