如何通过考试函数中的参数
本文关键字:函数 参数 何通过 考试 | 更新日期: 2023-09-27 18:05:05
我有这个函数:
public static IList<T> myFunction<T>(IList<T> listaCompleta, int numeroPacchetti)
{
return listaCompleta;
}
但是如果我用
来调用它IList<SomeObject> listPacchetti = (from SomeObject myso in SomeObjects
select myso).ToList();
listPacchetti = myFunction(listPacchetti, 1);
编译时显示The type arguments for method 'myFunction<T>(IList<T>, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
事实是,我需要使用一个列表(或一个集合索引,而不是一个IEnumerable),我需要传递一个通用对象给函数(这次是IList<SomeObject>
,下次可能是IList<AnotherObject>
)
我可以吗?或者是什么呢?我认为我不能使用IList作为类型参数…
EDIT -完整代码
从另一个类中调用函数
IList<Packet> listPacchetti = (from Packet pack in Packets
select pack).ToList();
listPacchetti = Utility.Extracts<Packet>(listPacchetti, 6);
CLASS WITH FUNCTION
public class Utility
{
public Utility()
{
}
public static IList<T> Extracts<T>(IList<T> listaCompleta, int numeroPacchetti) // HERE THERE IS THE LINE WITH WARNINGS
{
return listaCompleta;
}
}
您的实用程序类是为。net Framework 3.0或更高版本编译的,您的代码是否有对System.Collections.Generic
命名空间的引用?
那么,using System.Collections.Generic;
缺失了吗?
Markzzz:从你发布的关于IList
的错误,我怀疑你导入了错误的命名空间。你需要一个using System.Collections.Generic
在你的代码的顶部,我猜你有using System.Collections
。这就是为什么编译器告诉你IList
不能用作泛型。
试试这个;
public class SomeObject
{ }
public static List<T> MyFunction<T>(List<T> listaCompleta, int numeroPacchetti)
{
return listaCompleta;
}
static void Main(string[] args)
{
var someObjects = new List<SomeObject>();
var listPacchetti = (from SomeObject myso in someObjects
select myso).ToList();
listPacchetti = MyFunction<SomeObject>(listPacchetti, 1);
}