是否有一个"匿名"在C#中,像通用标签“?”在Java中? [英] Is there an "anonymous" generic tag in C#, like '?' in Java?
问题描述
在Java中,我们可以宣布一个未知泛型类型参数化的变量,它看起来像这样:
In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this:
Foo<?> x;
时有一个相当于构造这个问号,在C#中?
Is there an equivalent construct to this question-mark, in C#?
推荐答案
From C# from a Java developer's perspective by Dare Obasanjo:
在某些情况下,人们可能需要创建能够在含有相对于那些包含特定类型的任何类型的数据结构进行操作的方法(例如一个方法来打印在一个数据结构中的所有对象),同时仍然在仿制药服用的强类型的优势。在C#中指定这个机制是通过一个称为通用类型推断,而在Java中,这是使用通配符类型完成功能。下面的代码示例显示了这两种方法如何导致同样的结果。
In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result.
C#代码
using System;
using System.Collections;
using System.Collections.Generic;
class Test{
//Prints the contents of any generic Stack by
//using generic type inference
public static void PrintStackContents<T>(Stack<T> s){
while(s.Count != 0){
Console.WriteLine(s.Pop());
}
}
public static void Main(String[] args){
Stack<int> s2 = new Stack<int>();
s2.Push(4);
s2.Push(5);
s2.Push(6);
PrintStackContents(s2);
Stack<string> s1 = new Stack<string>();
s1.Push("One");
s1.Push("Two");
s1.Push("Three");
PrintStackContents(s1);
}
}
Java代码的
Java Code
import java.util.*;
class Test{
//Prints the contents of any generic Stack by
//specifying wildcard type
public static void PrintStackContents(Stack<?> s){
while(!s.empty()){
System.out.println(s.pop());
}
}
public static void main(String[] args){
Stack <Integer> s2 = new Stack <Integer>();
s2.push(4);
s2.push(5);
s2.push(6);
PrintStackContents(s2);
Stack<String> s1 = new Stack<String>();
s1.push("One");
s1.push("Two");
s1.push("Three");
PrintStackContents(s1);
}
}
这篇关于是否有一个"匿名"在C#中,像通用标签“?”在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!