假设我有一个通用类,如下所示:
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>
类继承自该类(或接口)的非泛型版本。
public class GeneralPropertyMap<T> : GeneralPropertyMap
{
}
public class GeneralPropertyMap
{
// Only you can implement it:
internal GeneralPropertyMap() { }
}
现在你可以这样做:
private void TakeGeneralPropertyMap(GeneralPropertyMap[] maps)
{
}
And:
GeneralPropertyMap[] maps = new GeneralPropertyMap[3];
maps[0] = new GeneralPropertyMap<String>();
maps[1] = new GeneralPropertyMap<Integer>();
maps[2] = new GeneralPropertyMap<Double>();
TakeGeneralPropertyMap(maps);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)