让我们说我有一个泛型类,如下所示:
Let's say I have a generic class as follows:
public class GeneralPropertyMap<T>
{
}
在其他类我有一个方法,需要在 GeneralPropertyMap&LT的数组; T&GT;
。在Java中,以便采取在包含任何类型的数组 GeneralPropertyMap
的方法是这样的:
In some other class I have a method that takes in an array of GeneralPropertyMap<T>
. In Java, in order to take in an array that contains any type of GeneralPropertyMap
the method would look like this:
private void TakeGeneralPropertyMap(GeneralPropertyMap<?>[] maps)
{
}
我们使用通配符,这样以后我们可以称之为 TakeGeneralPropertyMap
路过一堆 GeneralPropertyMap
与任何类型 T
每次,像这样的:
We use the wildcard so that later we can call TakeGeneralPropertyMap
passing a bunch of GeneralPropertyMap
with any type for T
each, like this:
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#中的等价物,但没有成功。任何想法?
I'm trying to figure out an equivalent in C# with no success. Any ideas?
泛型在C#中做出比Java泛型强大的保证。因此,你要在C#中的东西,你必须让 GeneralPropertyMap&LT; T&GT;
类继承的类(或接口)的非普通版
Generics in C# make stronger guarantees than generics in Java. Therefore, to do what you want in C#, you have to let the GeneralPropertyMap<T>
class inherit from a non-generic version of that class (or 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);
上一篇:转换的Uni code字符以ASCII最接近(最相似)字符(.NET)字符、最接近、相似、Uni
下一篇:如何设置JavaScriptSerializer格式化时,JSON序列化?如何设置、序列化、JavaScriptSerializer、JSON