非泛型中的泛型方法 class
Generic method inside non-generic class
我正在使用 .net Framework 4.0
我想在非泛型 class 中创建一个泛型方法
但它给了我编译时错误
错误:找不到类型或命名空间名称 'T'(是否缺少 using 指令或程序集引用?)
public class BlIAllClass
{
public static List<T> xyz()
{
List<T> cc = new List<T>();
return cc;
}
}
John Paul Jones 也提出了一个问题
Generic Method in non generic class
他在那里提到可以在非泛型 class.
中创建泛型方法
那我的代码有什么问题。
是框架版本相关的问题还是我遗漏了什么
您的方法不是通用的。 generic method is a method that is declared with type parameters.
将您的方法更改为:
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
您也可以将方法实现更改为:return new List<T>();
您需要在方法名称本身中指定泛型类型 <T>
,如下所示:
public class BlIAllClass
{
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
}
您需要将泛型类型参数添加到方法签名中。
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
是的,您可以在两个级别应用通用类型。您可以在方法级别和 Class 级别(两者都是可选的)应用泛型类型。如上例所示,您在方法级别应用了泛型类型,因此,您还必须在方法 return 类型和方法名称上应用泛型。
您需要更改一些代码。见下文。
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
我正在使用 .net Framework 4.0
我想在非泛型 class 中创建一个泛型方法
但它给了我编译时错误
错误:找不到类型或命名空间名称 'T'(是否缺少 using 指令或程序集引用?)
public class BlIAllClass
{
public static List<T> xyz()
{
List<T> cc = new List<T>();
return cc;
}
}
John Paul Jones 也提出了一个问题
Generic Method in non generic class
他在那里提到可以在非泛型 class.
中创建泛型方法
那我的代码有什么问题。
是框架版本相关的问题还是我遗漏了什么
您的方法不是通用的。 generic method is a method that is declared with type parameters.
将您的方法更改为:
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
您也可以将方法实现更改为:return new List<T>();
您需要在方法名称本身中指定泛型类型 <T>
,如下所示:
public class BlIAllClass
{
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
}
您需要将泛型类型参数添加到方法签名中。
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}
是的,您可以在两个级别应用通用类型。您可以在方法级别和 Class 级别(两者都是可选的)应用泛型类型。如上例所示,您在方法级别应用了泛型类型,因此,您还必须在方法 return 类型和方法名称上应用泛型。
您需要更改一些代码。见下文。
public static List<T> xyz<T>()
{
List<T> cc = new List<T>();
return cc;
}