我收到此错误:无法从用法中推断方法“ ConsoleApplication1.Program.takeList<T>
( )”的类型参数。System.ComponentModel.BindingList<T>
尝试明确指定类型参数。
我相信编译器无法猜测到 chooseList 方法的返回类型,但它必须将它传递给 takeList 方法。有没有办法使这项工作,但不能将 chooseList 方法解耦到 Main 函数中?
class Program
{
static BindingList<int> listOfInts;
static BindingList<string> listOfStrings;
//more lists
static void takeList<T>(BindingList<T> list)
{
//do something
return;
}
static object chooseList() //instead of object i would put BindingList<T>
{
int someCondition = 0;
//code that changes someCondition so compiler doesnt know its value
switch (someCondition)
{
case 1: return listOfInts;
//more cases for more lists
default: return listOfStrings;
}
}
static void Main(string[] args)
{
Program testClass = new Program();
var chosenList = chooseList();
takeList(chosenList);
}
}
编辑:
这是一个相反的情况,应该有效。我想把它转换成上面的:
class Program
{
static BindingList<int> listOfInts;
static BindingList<string> listOfStrings;
//more lists
static void takeList<T>(BindingList<T> list)
{
//do something
return;
}
static void Main(string[] args)
{
Program testClass = new Program();
int someCondition = 0;
//code that changes someCondition so compiler doesnt know its value
switch (someCondition)
{
case 1:
takeList(listOfInts);
break;
//more cases for more lists
default:
takeList(listOfStrings);
break;
}
//Instead of the switch here, i would like to write takelist(doTheSwitch(someCondition));
}
}