C#中是否存在“匿名”通用标记,如“?” 在Java?

在Java中,可以声明一个由“未知”generics类型参数化的变量,如下所示:

Foo x; 

在C#中,这个问号是否有一个等价的结构?

最简洁的答案是不。 C#中没有相同的function。

Dare Obasanjo 从Java开发人员的角度来看C#的解决方法:

在某些情况下,可能需要创建一个方法,该方法可以对包含任何类型的数据结构进行操作,而不是包含特定类型的数据结构(例如,打印数据结构中所有对象的方法),同时仍然可以利用在generics中打字很强。 在C#中指定它的机制是通过称为generics类型推理的function,而在Java中,这是使用通配符类型完成的。 以下代码示例显示了两种方法如何产生相同的结果。

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(Stack s){ while(s.Count != 0){ Console.WriteLine(s.Pop()); } } public static void Main(String[] args){ Stack s2 = new Stack(); s2.Push(4); s2.Push(5); s2.Push(6); PrintStackContents(s2); Stack s1 = new Stack(); s1.Push("One"); s1.Push("Two"); s1.Push("Three"); PrintStackContents(s1); } } 

Java代码

 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  s2 = new Stack (); s2.push(4); s2.push(5); s2.push(6); PrintStackContents(s2); Stack s1 = new Stack(); s1.push("One"); s1.push("Two"); s1.push("Three"); PrintStackContents(s1); } } 

AFAIK你不能用C#做到这一点。 BCL做了什么,并且有很多例子可以创建一个非generics的类,然后创建一个inheritance前一个基本行为的generics类。 见下面的例子。

 class Foo { } class Foo : Foo { } 

你可以写这样的东西:

 Foo t = new Foo(); 

虽然承认不是干净的方法,但使用Foox也可能是合适的。

C#中没有等效的语法。

C#中没有相应的东西,这是不完全正确的。 没有静态等效项可以用作类型,或者调用方法,就足够了。 为此,请使用Jorge的答案 。

另一方面,有时你需要相同的反思思想,并且在那里有一个等价物。 如果你有:

 interface IFoo { T Bar(T t, int n); } 

你可以使用typeof(IFoo)获得一个表示IFooType 。 鲜为人知,并且对您的问题的部分答案是,您还可以使用typeof(IFoo<>)获取表示IFooType

当你想通过reflection使用IFoo进行某些T时,这很有用,直到运行时才会知道T

 Type theInterface = typeof(IFoo<>); Type theSpecificInterface = theInterface.MakeGenericType(typeof(string)); // theSpecificInterface now holds IFoo even though we may not have known we wanted to use string until runtime // proceed with reflection as normal, make late bound calls / constructions, emit DynamicMethod code, etc. 

不,C#中的概念并不相同。 你需要引用一个Foo的基类(也许是一个非generics的Foo),或者让你在generics本身工作的方法(这样你就可以引用Foo了,让你的方法的调用者确定什么是T是)。

希望有所帮助。