返回类型为Collection<;T>;

本文关键字:gt lt 返回类型 Collection | 更新日期: 2023-09-27 18:25:14

我有一个函数,它应该返回一个Collection<T>型;它是T,因为Collection对象每次都会不同,这意味着函数的返回类型需要是泛型的。但是集合<当我将函数声明为public static Collection<T>func_name()。

有什么办法绕过这个吗?

谢谢。。。

返回类型为Collection<;T>;

您应该将其声明为

public static Collection<T> func_name<T>() ...

如果函数是在已经有泛型参数T的类中定义的,则可以删除第二个T。

你不能写:

public static Collection<T> func_name()
{
    // Implementation
}

函数如何知道返回什么类型?

您必须在方法声明中指定它需要指定T的类型:

public static Collection<T> func_name<T>()
{
    // Implementation
}
...
Collection<string> obj = func_name<string>();

请注意,在某些情况下,编译器可以推断所使用的类型(称为类型推断)。它不会更改方法声明,但可以简单地更改方法的用法:

public static Collection<T> func_name<T>(T param)
{
}
private static void Main(string[] args)
{
    string paramAsString = string.Empty;
    // Type inference here: the compiler know which is the type
    // represented by T as the parameter of the method that must 
    // be of type T is a string (so, for the compiler, T == string)
    // That's why in this example it's not required to write:
    // var obj = func_name<string>(paramAsString);
    // but following is enough:
    // var obj = func_name(paramAsString);
    Collection<string> obj = func_name(paramAsString);
    Console.ReadLine();
}

我建议你看看C#中的泛型。

将其声明为

public static Collection<T> func_name<T>()

这在C#中被称为"泛型",在某种程度上类似于C++模板类/函数。您可以在这篇MSDN文章中找到一些关于C#泛型的基本信息和许多有用的链接。

感谢您的帮助!

我已经决定序列化该函数,使其具有通用性。