我收到此错误:
方法“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));
}
}
答案 0 :(得分:1)
您需要的是BindingList<T>
派生自非通用抽象类型或界面BindingList
或IBindingList
。然后,您需要TakeList()
重载,它可以接受非泛型类型的某些内容。请注意,通用表单可能会影响抽象接口中的某些方法,以便例如Add(object)
将隐藏Add(T)
;其他方法可能会被重载,因此Contains(object)
和Contains(T)
都可以使用[前者可以检查List<Cat>
是否包含Animal
;即使Animal
不是Cat
派生的,Animal
类型的变量也可以包含对SiameseCat
实例的引用,但确实如此。