C#中是否有一个"匿名"通用标记,例如"?"?在Java中?

时间:2020-03-06 14:33:29  来源:igfitidea点击:

在Java中,可以声明由"未知"泛型类型参数化的变量,如下所示:

Foo<?> x;

在C#中,是否有与此问号等效的结构?

解决方案

不,C#中没有真正相同的概念。我们将需要引用Foo的基类(可能是非泛型Foo),或者使我们正在泛型中使用的方法(以便我们可以引用Foo,并让方法的调用者确定T是什么)。是)。

希望能有所帮助。

C#中没有等效的语法。

AFAIK,我们不能在C#中做到这一点。 BCL的作用是,有很多示例可以创建一个非通用的类,然后创建一个通用类来继承前一个的基本行为。请参见下面的示例。

class Foo
{
}

class Foo<T> : Foo
{
}

我们可以编写如下内容:

Foo t = new Foo<int>();

最简洁的答案是不。 C#中没有等效功能。

Dare Obasanjo从Java开发人员的角度出发,从C出发,采取一种变通方法:

在某些情况下,可能需要创建一种方法,该方法可以对包含任何类型的数据结构进行操作,而不是对包含特定类型的数据结构进行操作(例如,用于打印数据结构中所有对象的方法),同时仍要利用以下优点:强类型输入。在Cis中通过称为泛型类型推断的功能指定此机制的机制,而在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<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代码

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#中没有等效项是(完全)不正确的。没有可以用作类型或者调用方法的静态等效项就足够真实了。为此,请使用豪尔赫的答案。

另一方面,有时我们需要等效的想法进行反思,并且那里存在等效的想法。如果你有:

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

我们可以使用typeof(IFoo <int>)来表示" IFoo &lt;int>"的"类型"。鲜为人知的是,对于问题的部分答案是,我们还可以使用typeof(IFoo <>)获得代表Type'(IFoo &lt;T>)的Type

当我们想通过反射将" IFoo <T>"用于某些" T",并且直到运行时才知道" T"时,这很有用。

Type theInterface = typeof(IFoo<>);
Type theSpecificInterface = theInterface.MakeGenericType(typeof(string));

// theSpecificInterface now holds IFoo<string> 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.