C# 泛型中的通配符等效项 [英] Wildcard equivalent in C# generics

查看:34
本文介绍了C# 泛型中的通配符等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a generic class as follows:

public class GeneralPropertyMap<T>
{
}

在其他一些类中,我有一个方法接受 GeneralPropertyMap 的数组.在 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 传递一堆 GeneralPropertyMapT 的任何类型,如下所示:

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 类从该类(或接口)的非泛型版本继承.

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

这篇关于C# 泛型中的通配符等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆